QJsonDocument - getting values indented

3.6k Views Asked by At

I have a Json response like this:

{
  "data": [
    {
      "id": "someID", 
      "participants": {
        "data": [
          {
            "id": "idN1"
          }, 
          {
            "id": "idN2"
          }
        ]
      }
    },
    {
      "id": "someID", 
      "participants": {
        "data": [
          {
            "id": "idN3"
          }, 
          {
            "id": "idN4"
          }
        ]
      }
    }
  ]
} 

I want to get the second id array (the most indented ones) inside "participants".

My code is getting the value of the first id value intead of the ones inside participants. Here's my code:

QJsonDocument jsonResponse = QJsonDocument::fromJson(data.toUtf8());
QJsonObject jsonObject = jsonResponse.object();
QJsonArray jsonArray = jsonObject["data"].toArray();

foreach (const QJsonValue & value, jsonArray) {
    QJsonObject obj = value.toObject();

    if (obj["id"].toString()!=selfID) {
        myIdList.append(obj["id"].toString());
    }
}

I want to know how could I get rid of the ids less indented and get the most indented ones into myIdList.

Have a nice code!

1

There are 1 best solutions below

1
On BEST ANSWER

Here you go

#include <QList>
#include <QFile>

#include <QDebug>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>

int main(int argc, char *argv[])
{
    QFile file("/your/json-file/bla.json");
    file.open(QIODevice::ReadOnly);

    QString data = file.readAll();
    QString selfID = "2";

    QList<QString> myIdList = QList<QString>();

    QJsonDocument jsonResponse = QJsonDocument::fromJson(data.toUtf8());
    QJsonObject jsonObject = jsonResponse.object();
    QJsonArray jsonArray = jsonObject["data"].toArray();

    foreach (const QJsonValue & value, jsonArray) {
        QJsonObject obj = value.toObject();
        QString id = obj["id"].toString();

        if (id != selfID)
        {
            QJsonObject participants = obj["participants"].toObject();
            QJsonArray participants_data = participants["data"].toArray();

            foreach (const QJsonValue &data_element, participants_data)
            {
                QString inner_id = data_element.toObject()["id"].toString();
                myIdList.append(inner_id);
            }
        }
    }
    qDebug() << myIdList;

    return 0;
}