-1

I have exactly following json data as follows:

[
 {
  "id":"01323",
  "name":"Json Roy",
  "contacts":[
    "CONTACT1=+917673267299",
    "CONTACT2=+917673267292",
    "CONTACT3=+917673267293",
    "CONTACT4=+917673267294",
    ]
  }
]

I want to parse above jsonData data and extract contacts of that data.

QJsonParseError jerror;
QJsonDocument jsonData = QJsonDocument::fromJson(jsonData.c_str(),&jerror);
QJsonArray jsonArray = jsonData.array();
QJsonObject jsonObject = jsonData.object();
 foreach (const QJsonValue & value, jsonArray){

 string contact=jsonObject["contacts"].toString().toUtf8().constData();

}

can anybody suggest me how can i accomplish this with same above library?

Excoder
  • 37
  • 1
  • 7

1 Answers1

1

I removed latest comma in the contacts list.

Your mistake is treating QJsonValue as you want but QJsonValue is something like a wrapper so you should convert it to appropriate object ( array, object, string etc. ).

jsonData is not an object sojsonData.object() doesn't give you what you want.

Here is the code, it could be the starting point for you.

#include <QString>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonValue>
#include <QJsonParseError>
#include <QDebug>
#include <string>

int main(){

    auto json_input = R"([
    {
     "id":"01323",
     "name":"Json Roy",
     "contacts":[
       "CONTACT1=+917673267299",
       "CONTACT2=+917673267292",
       "CONTACT3=+917673267293",
       "CONTACT4=+917673267294"
       ]
     }
   ])";

    QJsonParseError err;

    auto doc = QJsonDocument::fromJson( QString::fromStdString( json_input ).toLatin1() , &err );
    auto objects = doc.array();

    if ( err.error != QJsonParseError::NoError )
    {
        qDebug() << err.errorString();
        return 1;
    }

    for( auto obj_val : objects )
    {
        auto obj = obj_val.toObject();

        auto contacts = obj.value( "contacts" ).toArray();

        for ( auto contact_val : contacts )
        {
            auto cotact_str = contact_val.toString();

            qDebug() << cotact_str;
        }
    }
}

Output :

CONTACT1=+917673267299 CONTACT2=+917673267292 CONTACT3=+917673267293 CONTACT4=+917673267294

calynr
  • 1,264
  • 1
  • 11
  • 23
  • ,why did you use backward slace ? – Excoder Mar 17 '20 at 11:45
  • `"` has special meaning in c++, so It is needed to use escape character which is `\\` . Also to inform the compiler that the line is resuming, so i appended escaping character end of the line. – calynr Mar 17 '20 at 11:49
  • @Excoder I edited for better understanding. https://en.cppreference.com/w/cpp/language/string_literal – calynr Mar 17 '20 at 11:54