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"
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.
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.
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.
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()); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With