How to parse a json file without a key?
-
Hi,
the file i want to parse is as follows.[
3,
"aabfff",
{
"currentTime": "2022-03-22T14:21:17.416524",
"interval":10,
"status":"Accepted"
}
]i would like to get each item by index if possible.
I don't know how to parse it.
In particular, I have no idea how to get <3, "aabfff"> without a Key value.
If you know how, please advise. -
@dennis-kim said in How to parse a json file without a key?:
I have no idea how to get <3, "aabfff"> without a Key value
Using index. You have an array, so use index.
Read your JSON into QJsonDocument using https://doc.qt.io/qt-5/qjsondocument.html#fromJson
Then convert QJsonDocument to array using https://doc.qt.io/qt-5/qjsondocument.html#array
Then access array elements using https://doc.qt.io/qt-5/qjsonarray.html#operator-5b-5d -
@dennis-kim the top level is QJsonArray, you can just iterate over it, can't you?
PS. @jsulm was faster ;)
-
The text representation of JSON encloses arrays in square brackets ([ ... ]) and objects in curly brackets ({ ... }). Entries in arrays and objects are separated by commas. The separator between keys and values in an object is a colon (:).
(https://doc.qt.io/qt-5/json.html)
So, what you have here is a JSON, which contains an array of ints, strings and json objects...
Edit:
LOL, didn't refresh my page... thought, I'd be the first :) sry @jsulm @artwaw :D -
thanks a lot...
Solved this issue.**QByteArray json_bytes = json_msg->toLocal8Bit(); QJsonDocument doc = QJsonDocument::fromJson(json_bytes, &err); QJsonArray jsonArray = doc.array(); QJsonValue abc = jsonArray[0]; qDebug() << "abc:" << abc << "type : " << abc.type(); abc = jsonArray[1]; qDebug() << "abc1:" << abc << "type : " << abc.type(); abc = jsonArray[2]; qDebug() << "abc2:" << abc << "type : " << abc.type(); for (auto it = jsonArray.constBegin(); it != jsonArray.constEnd(); ++it) { const QJsonValue &val = *it; QJsonObject o = val.toObject(); for (auto oIt = o.constBegin(); oIt != o.constEnd(); ++oIt) { qDebug() << "Key:" << oIt.key() << ", Value:" << oIt.value().toString(); } }**