QJsonValue::toArray() wraps correct json array inside another array
Unsolved
General and Desktop
-
(QT 6.8.1 on linux with cmake)I found this weird behavior where the QJsonValue::toArray function returns the correct array, but wrapped inside another array and I'm not sure if I'm using the library correctly:
file.json:{ "success": true, "value_1": false, "array": [ { "some_value_A": "AAA", "value_1" : "111" }, { "some_value_B": "BBB", "value_2" : "222" }, { "some_value_C": "CCC", "value_3" : "333" } ] }
C++ Code:
const QJsonDocument json_doc{ json_document_from_file }; qDebug() << "json_doc.isObject() = " << json_doc.isObject(); // prints true const QJsonObject object{ json_doc.object() }; qDebug() << "object.contains(\"array\") = " << object.contains("array"); //prints true qDebug() << "object.size() = " << object.size(); //prints 3 const QJsonValue value{ object["array"] }; qDebug() << "value.isArray() = " << value.isArray(); //prints true const QJsonArray array{ value.toArray() }; qDebug() << "array.size() = " << array.size() << "\t Should be 3"; //prints 1 qDebug() << "array.at(0).toArray().size() = " << array.at(0).toArray().size() << "\t Should be 3"; //prints 3 qDebug() << "value.toArray().size() = " << value.toArray().size() << "\t Should be 3"; //prints 3
-
Hi, it's easy to wrap JSON in too many layers, I think the culprit is this line
....
const QJsonArray array{ value.toArray() };
...
I think that QJSonArray array is a double wrapper, that's why you get size() = 1, because that's the size of the outer array (i.e. the outer array has 1 element, which is one array which has 3 elements :-).