How to add QJsonArray to QJsonObject ?



  • Hi ;

    I have QJsonArray and QJsonObject. But I want to add only 0th. index.

    QJsonObject data = QJsonObject(
    {
    qMakePair(QString("operator"),QJsonValue(oprt)),
    qMakePair(QString("sample"), QJsonValue(sample)),
    qMakePair(QString("moisture content"), QJsonValue(moisture)),
    qMakePair(QString("weight"), QJsonValue(weight)),
    qMakePair(QString("absorption"), QJsonValue(absorption)),
    qMakePair(QString("remark"), QJsonValue(remark))
    });
    
    plotJSON.push_back(QJsonValue(data));
    

    If I use push_back func. I can add same two or more info. In my program this value added only one time. I try fallowing code block to add 0th. index. But it's not working. How can I add specific index to QJsonvalue?

      insertArrayAt(plotJSON,0,QJsonValue(data));     
      plotJSON.insert(0, data);

  • Moderators

    Hi! I don't exactly understand what you want to do. Can you give an example?



  • Hi @HafsaElif,

    As @Wieland said, its not entirely clear what you mean, but I suspect you're trying to differentiate between inserting items at a specific index, versus assigning them to an index.

    For example, if you invoke plotJSON.insert(0, data) multiple times, you will get many copies of data at different indexes starting at 0, because each time it prepends the item (at position 0). Whereas, if you did plotJSONp[0] = data multiple times, then you will end up just updating the same item at index 0 each time.

    A quick demo to show the difference:

        // Two identical JSON arrays.
        QJsonArray plotJSON_A;
        plotJSON_A.push_back(1);
        plotJSON_A.push_back(2);
        plotJSON_A.push_back(3);
        QJsonArray plotJSON_B = plotJSON_A;
    
        // A sample JSON object.
        QJsonObject data;
        data.insert(QStringLiteral("foo"), 456);
        data.insert(QStringLiteral("bar"), 789);
    
        qDebug() << "Before" << plotJSON_A;
        plotJSON_A.insert(0, data); ///< data is prepended to the array.
        plotJSON_B[0] = data; ///< value at index 0 is overwritten with data.
        qDebug() << "AfterA" << plotJSON_A;
        qDebug() << "AfterB" << plotJSON_B;
    
    

    Output:

    Before QJsonArray([1,2,3])
    AfterA QJsonArray([{"bar":789,"foo":456},1,2,3])
    AfterB QJsonArray([{"bar":789,"foo":456},2,3])
    

    In both cases, data is added at index 0, but in the first case its prepended, pushing all the existing items along in indices. In the second case, the indices for the existing items remains the same, but one value (1) is now gone (overwritten).

    I hope that helps. But if not, as @Wieland suggested, try expanding on the question a little, ideally using an example or two :)

    Cheers.



  • @Paul-Colby thank you for answer it was work :)


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.