Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. how to use JSON from QJsonValue ?
Forum Updated to NodeBB v4.3 + New Features

how to use JSON from QJsonValue ?

Scheduled Pinned Locked Moved Solved General and Desktop
6 Posts 4 Posters 2.0k Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • X Offline
    X Offline
    Xena_o
    wrote on 15 Apr 2021, 17:08 last edited by
    #1

    hello,
    i am sending an url GET request that returns a response into JSON format inside QJsonValue, i can see there is a bunch of data (many records) when outputing with qDebug()

    The thing is i dont know how to use the data... toString() doesnt convert anything or something like data[rowNumber][fieldName] doesnt print out anything.

    void MainWindow::onResult(QNetworkReply *reply){
        if(reply->error() == QNetworkReply::NoError){
    
    
            QByteArray result = reply->readAll();
            //qDebug()<< result;
            QJsonDocument jsonResponse = QJsonDocument::fromJson(result);
            QJsonObject obj = jsonResponse.object();
    
            double info1= obj["info1"].toDouble();
            QJsonValue info2= obj["info2"];
            QJsonValue info3= obj["info3"]; //<== nested json (many records)
            QJsonValue info4= obj["info4"];
    
            QJsonDocument jd_i3(info3.toObject());
            QJsonObject obj_i3 = jd_i3.object();
    
            qDebug()<< obj_i3["info5"]; // data here, many records nested JSON
    
    //what to do now ?
        }
        else
            qDebug() << "ERROR";
        reply->deleteLater();
    }
    

    i would like to get the data into qstring array or something to be able to access them by row number and field name.

    Any help would be great.

    Thank you

    1 Reply Last reply
    0
    • M Offline
      M Offline
      mrjj
      Lifetime Qt Champion
      wrote on 15 Apr 2021, 17:55 last edited by
      #2

      Hi
      What is the "nested" json you talk about ?
      Normally it would be a jsonArray with objects or similar and you would
      then use QJsonArray and not QJsonValue.

      1 Reply Last reply
      2
      • X Offline
        X Offline
        Xena_o
        wrote on 16 Apr 2021, 13:43 last edited by
        #3

        hi

        in my example
        info1, info 2 and info3 return single value

        info3 returns mutiple records, multiple rows of same kind of data (this what i mean by nested json)

        how to get this all data in a usable manner, because in QJasonValue i feel i can do nothing with that.

        Is QjasonArray better ? would you kindly show me an example of use ?

        thanks

        J A 2 Replies Last reply 16 Apr 2021, 18:51
        0
        • X Xena_o
          16 Apr 2021, 13:43

          hi

          in my example
          info1, info 2 and info3 return single value

          info3 returns mutiple records, multiple rows of same kind of data (this what i mean by nested json)

          how to get this all data in a usable manner, because in QJasonValue i feel i can do nothing with that.

          Is QjasonArray better ? would you kindly show me an example of use ?

          thanks

          J Offline
          J Offline
          JonB
          wrote on 16 Apr 2021, 18:51 last edited by JonB
          #4

          @Xena_o
          I think you are misunderstanding something. QJsonValue can hold several types of values: simple value like QJsonValue::String but also complex value like QJsonValue::Array. Read https://doc.qt.io/qt-5/qjsonvalue.html#details. These are all the types representable in a JSON document, there isn't anything else.

          Look at the QJsonValue::Type QJsonValue::type() const and act accordingly in your code. For example, if your info3 is a JSON array use QJsonArray QJsonValue::toArray() const to get a QJsonArray. Or you could use QVariant QJsonValue::toVariant() const to get one of Qt types listed there if you prefer.

          1 Reply Last reply
          1
          • X Xena_o
            16 Apr 2021, 13:43

            hi

            in my example
            info1, info 2 and info3 return single value

            info3 returns mutiple records, multiple rows of same kind of data (this what i mean by nested json)

            how to get this all data in a usable manner, because in QJasonValue i feel i can do nothing with that.

            Is QjasonArray better ? would you kindly show me an example of use ?

            thanks

            A Offline
            A Offline
            Alvein
            wrote on 17 Apr 2021, 18:37 last edited by Alvein
            #5

            @Xena_o I think you should understand the basics of the JSON format first.

            Try looking at this sample which may cover everything you need.

            From that sample, notice that:

            • info1 is a single vale (number)

            • info2 is a single value (string)

            • info3 is an array of numbers

            • info4 is an object (a nested JSON object)

            • info4.a is a single value (number)

            • info4.b is a single value (string)

            • info4.c is an array of numbers

            • info5 is an array of objects (nested JSON objects)

            • info5[].x is a single value (number)

            • info5[].y is a single value (string)

            Now check the code for parsing that sample:

            void test() {
                QString               sJSONURL,
                                      sJSONContent;
                QNetworkAccessManager namManager;
                QNetworkRequest       nrqJSON;
                QNetworkReply         *nrpJSON;
                sJSONURL="https://jsonblob.com/api/jsonBlob/315141b9-9f9e-11eb-a8a5-013bfcee1bdc";
                nrqJSON.setUrl(QUrl(sJSONURL));
                nrpJSON=namManager.get(nrqJSON);
                while(!nrpJSON->isFinished())
                    QApplication::processEvents(QEventLoop::ProcessEventsFlag::ExcludeUserInputEvents);
                if(QNetworkReply::NetworkError::NoError==nrpJSON->error()) {
                    int     iResCode;
                    QString sContentType;
                    iResCode=nrpJSON->attribute(QNetworkRequest::Attribute::HttpStatusCodeAttribute).toInt();
                    sContentType=nrpJSON->header(QNetworkRequest::KnownHeaders::ContentTypeHeader).toString();
                    if(200==iResCode)
                        if(0==sContentType.indexOf("application/json")) {
                            sJSONContent=nrpJSON->readAll();
                            // JSON parsing begins here
                            int             iDebug;
                            QList<double>   dblDebug;
                            QJsonDocument   jsnDoc;
                            QJsonObject     jsnObj;
                            QJsonArray      jsnArr;
                            QJsonParseError jsnErr;
                            jsnDoc=QJsonDocument::fromJson(sJSONContent.toUtf8(),&jsnErr);
                            if(!jsnDoc.isNull()) {
                                // info1
                                if(jsnDoc.object().contains("info1"))
                                    if(jsnDoc.object().value("info1").isDouble())
                                        qDebug() << "info1" << jsnDoc.object().value("info1").toDouble();
                                // info2
                                if(jsnDoc.object().contains("info2"))
                                    if(jsnDoc.object().value("info2").isString())
                                        qDebug() << "info2" << jsnDoc.object().value("info2").toString();
                                // info3
                                if(jsnDoc.object().contains("info3"))
                                    if(jsnDoc.object().value("info3").isArray()) {
                                        jsnArr=jsnDoc.object().value("info3").toArray();
                                        dblDebug.clear();
                                        for(auto v:jsnArr)
                                            if(v.isDouble())
                                                dblDebug.append(v.toDouble());
                                        qDebug() << "info3" << dblDebug;
                                    }
                                // info4
                                if(jsnDoc.object().contains("info4"))
                                    if(jsnDoc.object().value("info4").isObject()) {
                                        jsnObj=jsnDoc.object().value("info4").toObject();
                                        if(jsnObj.contains("a"))
                                            if(jsnObj.value("a").isDouble())
                                                qDebug() << "info4.a" << jsnObj.value("a").toDouble();
                                        if(jsnObj.contains("b"))
                                            if(jsnObj.value("b").isString())
                                                qDebug() << "info4.b" << jsnObj.value("b").toString();
                                        if(jsnObj.contains("c"))
                                            if(jsnObj.value("c").isArray()) {
                                                jsnArr=jsnObj.value("c").toArray();
                                                dblDebug.clear();
                                                for(auto v:jsnArr)
                                                    if(v.isDouble())
                                                        dblDebug.append(v.toDouble());
                                                qDebug() << "info4.c" << dblDebug;
                                            }
                                    }
                                // info5
                                if(jsnDoc.object().contains("info5"))
                                    if(jsnDoc.object().value("info5").isArray()) {
                                        jsnArr=jsnDoc.object().value("info5").toArray();
                                        iDebug=0;
                                        for(auto v:jsnArr) {
                                            if(v.isObject()) {
                                                jsnObj=v.toObject();
                                                if(jsnObj.contains("x"))
                                                    if(jsnObj.value("x").isDouble())
                                                        qDebug() << QString("info5[%1].x").arg(iDebug) <<
                                                                    jsnObj.value("x").toDouble();
                                                if(jsnObj.contains("y"))
                                                    if(jsnObj.value("y").isString())
                                                        qDebug() << QString("info5[%1].y").arg(iDebug) <<
                                                                    jsnObj.value("y").toString();
                                            }
                                            iDebug++;
                                        }
                                    }
                            }
                            else
                                qDebug() << "JSON parse failed:" << jsnErr.errorString();
                        }
                        else
                            qDebug() << "unexpected content type:" << sContentType;
                    else
                        qDebug() << "unexpected response code:" << iResCode;
                }
                else
                    qDebug() << "request failed:" << nrpJSON->errorString();
                nrpJSON->~QNetworkReply();
            }
            

            Hope this helps.

            1 Reply Last reply
            1
            • X Offline
              X Offline
              Xena_o
              wrote on 17 Apr 2021, 21:00 last edited by
              #6

              @JonB thank you

              @Alvein thank you , your example is great, i could figure out how to read the data response. so far its like guessing whats inside the data packet.
              thanks a lot :-)

              1 Reply Last reply
              0

              1/6

              15 Apr 2021, 17:08

              • Login

              • Login or register to search.
              1 out of 6
              • First post
                1/6
                Last post
              0
              • Categories
              • Recent
              • Tags
              • Popular
              • Users
              • Groups
              • Search
              • Get Qt Extensions
              • Unsolved