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. |HELP| : How to extract Data from Json file ?

|HELP| : How to extract Data from Json file ?

Scheduled Pinned Locked Moved Solved General and Desktop
11 Posts 5 Posters 4.2k Views
  • 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.
  • ElmehdiE Offline
    ElmehdiE Offline
    Elmehdi
    wrote on last edited by Elmehdi
    #1

    I have a Json file wich has the format starting with a "[" , and has objects inside it, each object has its own attributes. My purpose is to retrieve these data of each object and insert it in a database, that's another talk but for the moment I want just to print them. I was struggling with this for about 4 days without finding what I need.
    here is an example of my file :

    [
     {
        "updated":1592183850402,
        "country":"Morocco",
        "countryInfo":
        {"_id":504,
            "iso2":"MA",
            "iso3":"MAR",
            "lat":32,
            "continent":"Africa",
            "activePerOneMillion":22.12
        }
    },
    {
        "updated":159388477402,
        "country":"France",
        "countryInfo":
        {"_id":504,
            "iso2":"FR",
            "iso3":"FRA",
            "lat":332,
            "continent":"Europe",
            "activePerOneMillion":66.12
        }
    }
    ]
    

    And I really need help, since I'm new to both Qt and Json I can't go so far by myself. if any one can help me with a piece of code.
    this is what I wrote, but whenever I reache the foreach loop I can't figure out my next move. I have tried different ways inside the loop but none of it worked.

        QTextStream file_text(&my_json);
        QString json_string;
        json_string = file_text.readAll();
        my_json.close();
        QByteArray json_bytes = json_string.toLocal8Bit();
        auto json_doc = QJsonDocument::fromJson(json_bytes);
        QJsonObject json_obj = json_doc.object();
        QJsonArray jsonArray = json_obj["activePerOneMillion"].toArray();
    
        foreach (const QJsonValue & value, jsonArray) { ... }
    
    Pablo J. RoginaP JonBJ 2 Replies Last reply
    0
    • ElmehdiE Offline
      ElmehdiE Offline
      Elmehdi
      wrote on last edited by Elmehdi
      #11

      Thank you all. And a special thanks to @LeLev who helped me in private. apparently the base-ranged for loop helped me since it reconizes the type of objects that are stored in the QjsonArray so it access them all. This was what worked for me:

       QFile countries_file("countries.json");
          QFile morocco_file("morocco.json");
          QString json_string;
      
          if(countries_file.open(QIODevice::ReadOnly | QIODevice::Text)){
              json_string = countries_file.readAll();
              countries_file.close();
          }
          else
              qDebug()<< "file not found";
          auto json_doc = QJsonDocument::fromJson(json_string.toUtf8());
      
          QJsonArray jArr = json_doc.array();
      QJsonValue val;
          for(auto jsonObj : jArr)
          {
              val = jsonObj.toObject().value("country");
              _country = val.toString();
              qDebug() << "Country: "<< _country;
      
              val = jsonObj.toObject().value("cases");
              _cases = val.toInt();
              qDebug() << "Cases: "<< _cases;
      
              val = jsonObj.toObject().value("deaths");
              _deaths = val.toInt();
              qDebug() << "Deaths: "<< _deaths;
         }
      
      
              qDebug() << Qt::endl;
              qDebug() << Qt::endl;
      
      
      1 Reply Last reply
      3
      • mrjjM Offline
        mrjjM Offline
        mrjj
        Lifetime Qt Champion
        wrote on last edited by mrjj
        #2

        Hi and welcome to the forums.
        You seem off to a good start.
        What you have is a json array with objects in it.

        So in you for loop you will get QJsonObject and not a
        QJsonValue if i read it correctly :=)

        Nope. @JonB is right :)

        1 Reply Last reply
        2
        • ElmehdiE Elmehdi

          I have a Json file wich has the format starting with a "[" , and has objects inside it, each object has its own attributes. My purpose is to retrieve these data of each object and insert it in a database, that's another talk but for the moment I want just to print them. I was struggling with this for about 4 days without finding what I need.
          here is an example of my file :

          [
           {
              "updated":1592183850402,
              "country":"Morocco",
              "countryInfo":
              {"_id":504,
                  "iso2":"MA",
                  "iso3":"MAR",
                  "lat":32,
                  "continent":"Africa",
                  "activePerOneMillion":22.12
              }
          },
          {
              "updated":159388477402,
              "country":"France",
              "countryInfo":
              {"_id":504,
                  "iso2":"FR",
                  "iso3":"FRA",
                  "lat":332,
                  "continent":"Europe",
                  "activePerOneMillion":66.12
              }
          }
          ]
          

          And I really need help, since I'm new to both Qt and Json I can't go so far by myself. if any one can help me with a piece of code.
          this is what I wrote, but whenever I reache the foreach loop I can't figure out my next move. I have tried different ways inside the loop but none of it worked.

              QTextStream file_text(&my_json);
              QString json_string;
              json_string = file_text.readAll();
              my_json.close();
              QByteArray json_bytes = json_string.toLocal8Bit();
              auto json_doc = QJsonDocument::fromJson(json_bytes);
              QJsonObject json_obj = json_doc.object();
              QJsonArray jsonArray = json_obj["activePerOneMillion"].toArray();
          
              foreach (const QJsonValue & value, jsonArray) { ... }
          
          Pablo J. RoginaP Offline
          Pablo J. RoginaP Offline
          Pablo J. Rogina
          wrote on last edited by
          #3

          @Elmehdi said in |HELP| : How to extract Data from Json file ?:

          I'm new to both Qt and Json

          Just in case, have you read the documentation?

          There's even a good example...

          Upvote the answer(s) that helped you solve the issue
          Use "Topic Tools" button to mark your post as Solved
          Add screenshots via postimage.org
          Don't ask support requests via chat/PM. Please use the forum so others can benefit from the solution in the future

          1 Reply Last reply
          1
          • ElmehdiE Elmehdi

            I have a Json file wich has the format starting with a "[" , and has objects inside it, each object has its own attributes. My purpose is to retrieve these data of each object and insert it in a database, that's another talk but for the moment I want just to print them. I was struggling with this for about 4 days without finding what I need.
            here is an example of my file :

            [
             {
                "updated":1592183850402,
                "country":"Morocco",
                "countryInfo":
                {"_id":504,
                    "iso2":"MA",
                    "iso3":"MAR",
                    "lat":32,
                    "continent":"Africa",
                    "activePerOneMillion":22.12
                }
            },
            {
                "updated":159388477402,
                "country":"France",
                "countryInfo":
                {"_id":504,
                    "iso2":"FR",
                    "iso3":"FRA",
                    "lat":332,
                    "continent":"Europe",
                    "activePerOneMillion":66.12
                }
            }
            ]
            

            And I really need help, since I'm new to both Qt and Json I can't go so far by myself. if any one can help me with a piece of code.
            this is what I wrote, but whenever I reache the foreach loop I can't figure out my next move. I have tried different ways inside the loop but none of it worked.

                QTextStream file_text(&my_json);
                QString json_string;
                json_string = file_text.readAll();
                my_json.close();
                QByteArray json_bytes = json_string.toLocal8Bit();
                auto json_doc = QJsonDocument::fromJson(json_bytes);
                QJsonObject json_obj = json_doc.object();
                QJsonArray jsonArray = json_obj["activePerOneMillion"].toArray();
            
                foreach (const QJsonValue & value, jsonArray) { ... }
            
            JonBJ Online
            JonBJ Online
            JonB
            wrote on last edited by JonB
            #4

            @Elmehdi
            With all die respect to my learned friend @mrjj, you do get QJsonValues as you iterate through QJsonArray jsonArray.

            The point is, a QJsonValue can hold many data types (see https://doc.qt.io/qt-5/qjsonvalue.html#details). In your case those will be QJsonObjects. The first thing you should write in your code is:

            foreach (const QJsonValue & value, jsonArray)
            {
                qDebug() << value.type();
            }
            

            and look at the values per https://doc.qt.io/qt-5/qjsonvalue.html#Type-enum.

            From there, you will probably also want to look at QJsonObject QJsonValue::toObject() and/or QVariant QJsonValue::toVariant().

            If you know about recursion, that will be pretty handy when parsing JSON data.

            1 Reply Last reply
            2
            • mrjjM Offline
              mrjjM Offline
              mrjj
              Lifetime Qt Champion
              wrote on last edited by
              #5

              Hi
              I think what confused me is this
              QJsonArray jsonArray = json_obj["cases"].toArray();
              i dont see "cases" in the data sample.

              JonBJ 1 Reply Last reply
              1
              • mrjjM mrjj

                Hi
                I think what confused me is this
                QJsonArray jsonArray = json_obj["cases"].toArray();
                i dont see "cases" in the data sample.

                JonBJ Online
                JonBJ Online
                JonB
                wrote on last edited by
                #6

                @mrjj
                I did indeed intend to mention to @Elmehdi : if that is the complete JSON file, nothing there matches with the json_obj["cases"] in your code, I don't know where your idea of the "cases" comes from.

                1 Reply Last reply
                0
                • ODБOïO Offline
                  ODБOïO Offline
                  ODБOï
                  wrote on last edited by ODБOï
                  #7

                  it is not valide json format, you have to delete the semicolon at the end of last lines "activePerOneMillion":66.12,

                  mrjjM 1 Reply Last reply
                  2
                  • ODБOïO ODБOï

                    it is not valide json format, you have to delete the semicolon at the end of last lines "activePerOneMillion":66.12,

                    mrjjM Offline
                    mrjjM Offline
                    mrjj
                    Lifetime Qt Champion
                    wrote on last edited by
                    #8

                    @LeLev
                    Thats good spotting!

                    1 Reply Last reply
                    1
                    • ElmehdiE Offline
                      ElmehdiE Offline
                      Elmehdi
                      wrote on last edited by
                      #9

                      Thank you guys, I didn't expect the fast answers, that was great. @mrjj sorry there is no field with that name I corrected it.
                      @JonB I will check that immediately thanks.

                      1 Reply Last reply
                      0
                      • ElmehdiE Offline
                        ElmehdiE Offline
                        Elmehdi
                        wrote on last edited by
                        #10

                        @LeLev you are right I just made a mistake while copying since it was not the whole file it was just a part of it, I fixed it now.

                        1 Reply Last reply
                        0
                        • ElmehdiE Offline
                          ElmehdiE Offline
                          Elmehdi
                          wrote on last edited by Elmehdi
                          #11

                          Thank you all. And a special thanks to @LeLev who helped me in private. apparently the base-ranged for loop helped me since it reconizes the type of objects that are stored in the QjsonArray so it access them all. This was what worked for me:

                           QFile countries_file("countries.json");
                              QFile morocco_file("morocco.json");
                              QString json_string;
                          
                              if(countries_file.open(QIODevice::ReadOnly | QIODevice::Text)){
                                  json_string = countries_file.readAll();
                                  countries_file.close();
                              }
                              else
                                  qDebug()<< "file not found";
                              auto json_doc = QJsonDocument::fromJson(json_string.toUtf8());
                          
                              QJsonArray jArr = json_doc.array();
                          QJsonValue val;
                              for(auto jsonObj : jArr)
                              {
                                  val = jsonObj.toObject().value("country");
                                  _country = val.toString();
                                  qDebug() << "Country: "<< _country;
                          
                                  val = jsonObj.toObject().value("cases");
                                  _cases = val.toInt();
                                  qDebug() << "Cases: "<< _cases;
                          
                                  val = jsonObj.toObject().value("deaths");
                                  _deaths = val.toInt();
                                  qDebug() << "Deaths: "<< _deaths;
                             }
                          
                          
                                  qDebug() << Qt::endl;
                                  qDebug() << Qt::endl;
                          
                          
                          1 Reply Last reply
                          3

                          • Login

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