Get value from QJsonObject by index

15.8k Views Asked by At

In my app I use json object to get result from remote database. Usually response string looks like:

{
    status:"ok",
    data: [
        { field1:"value1", field2:"value2", field3:"value3" },
        { field1:"value4", field2:"value5", field3:"value6" },
        { field1:"value7", field2:"value8", field3:"value9" }
    ]
}

It looks good and I can get value from speciified row/col by:

QJsonDocument jsonResponse = QJsonDocument::fromJson(strReply.toUtf8());
QJsonObject responseObject = jsonResponse.object();
if(responseObject.value("status").toString() == "ok") {
     QJsonArray dataObject = responseObject.value("data").toArray();
     // and here I can get the value, for example 2-nd row, field2
     QString value = dataObject.at(1).toObject().value("field2").toString(); 
}

But sometimes I need to get the value not by name but by index. Ok, I do following:

QJsonObject obj = dataObject.at(1).toObject();
QString key = obj.keys().at(1); // I use index here instead of name
QString value = obj.value(key).toString();

But unfortunately it looks that keys() not preserves field order so key with index 0 not exactly will be first field in its QJsonObject.

So my question - how can I get appropriate field from QJsonObject by index and not by name only?

1

There are 1 best solutions below

0
On

first suggestion : maybe you can use this code instead, which is more readable

responseObject["status"].toString() == "ok"

and here is your question suggestion

maybe you can try iterator, the below code just the example:

QJsonArray dataObject = responseObject["data"].toArray();
QJsonArray::iterator it;
for (it = dataObject.begin(); it != dataObject.end(); it++) {
    QString key = it->first;
    QString value = it->second;
}