Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QJsonObject: Access Element tree



  • Looking this JSON example below, how can I access the value of this JSON property called c using Qt 5 JSON API?

    {
      "my_array": [
        {
          "a": {
            "b": {
              "c": 10
            }
          }
        },
        {
          "a": {
            "b": {
              "c": 20
            }
          }
        }
      ]
    }
    

    I was thinking that could be something like this:

    // Get the first object:
    int c0 = my_json["my_array"][0]["a"]["b"]["c"].toInt();
    // c0 = 10;
    
    // Get the second object:
    int c1 = my_json["my_array"][1]["a"]["b"]["c"].toInt();
    // c1 = 20;
    

    How can I get this c0 ans c1 values?



  • First you need to use QJsonDocument to get the json from text.

    Once you get it into a document, start breaking it apart. From your structure you want an object first. You get the value from your object using your key.

    Since it is a little hard to explain here is a small example which could help get you started. I read your JSON from a file test.json and prints out "C0" and "C1" like you are asking.

    #include <QApplication>
    #include <QFile>
    #include <QJsonDocument>
    #include <QJsonArray>
    #include <QJsonObject>
    
    #include <QDebug>
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
    //    MainWindow w;
    //    w.show();
    
        QFile mFile("test.json");
        if (!mFile.open(QIODevice::ReadOnly))
        {
            qDebug() << "Unable to open file";
            return 0;
        }
    
        QJsonDocument mDoc;
        mDoc = QJsonDocument::fromJson(mFile.readAll());
        if (!mDoc.isObject())
        {
            qDebug() << "JSON not formatted properly or is not an object.";
            return 0;
        }
    
        qDebug() << mDoc.object().value("my_array").toArray().size();
        
        int c0 = mDoc.object().value("my_array").toArray().at(0).toObject().value("a").toObject().value("b").toObject().value("c").toInt();
        int c1 = mDoc.object().value("my_array").toArray().at(1).toObject().value("a").toObject().value("b").toObject().value("c").toInt();
        qDebug() << c0 << c1;
    
        return a.exec();
    }
    


  • @mrshawn thank you so much! That's perfect!


Log in to reply