Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt parsing JSON using QJsonDocument, QJsonObject, QJsonArray

Tags:

json

qt

I'm using Qt5. I am trying to obtain values from a json object. Here is what the json object looks like that I am trying to get data from:

{     "success": true,     "properties": [         {             "ID": 1001,             "PropertyName": "McDonalds",             "key": "00112233445566778899aabbccddeeff"         },         {             "ID": 1002,             "PropertyName": "Burger King",             "key": "10112233445566778899aabbccddeeff"         },         {             "ID": 1003,             "PropertyName": "Taco Bell",             "key": "20112233445566778899aabbccddeeff"         }     ] } 

How can I create three arrays that contain properties[x].ID, properties[x].PropertyName, and properties[x].key in Qt?

Edit:

Using QScriptEngine I tried this:

QString data = (QString)reply->readAll();  QScriptEngine engine;  QScriptValue result = engine.evaluate(data);  qDebug() << result.toString(); 

Debug is saying "SyntaxError: Parse error"

like image 663
Jared Price Avatar asked Nov 06 '13 20:11

Jared Price


People also ask

Does Qt support JSON?

Qt provides support for dealing with JSON data. JSON is a format to encode object data derived from Javascript, but now widely used as a data exchange format on the internet. The JSON support in Qt provides an easy to use C++ API to parse, modify and save JSON data.

What is JSONPath parse?

JSONPath is an expression language to parse JSON data. It's very similar to the XPath expression language to parse XML data. The idea is to parse the JSON data and get the value you want.

How JSON array looks like?

A JSON array contains zero, one, or more ordered elements, separated by a comma. The JSON array is surrounded by square brackets [ ] . A JSON array is zero terminated, the first index of the array is zero (0). Therefore, the last index of the array is length - 1.


1 Answers

I figured it out:

QStringList propertyNames; QStringList propertyKeys; QString strReply = (QString)reply->readAll(); QJsonDocument jsonResponse = QJsonDocument::fromJson(strReply.toUtf8()); QJsonObject jsonObject = jsonResponse.object(); QJsonArray jsonArray = jsonObject["properties"].toArray();  foreach (const QJsonValue & value, jsonArray) {     QJsonObject obj = value.toObject();     propertyNames.append(obj["PropertyName"].toString());     propertyKeys.append(obj["key"].toString()); } 
like image 145
Jared Price Avatar answered Sep 16 '22 19:09

Jared Price