Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse QJsonArray?

Tags:

c++

json

qt

In my QT application, there is a need to store the value of structures of the same type in a JSON dictionary. I know about the [JSON Save Game Example article][1], I tried to figure it out for a long time, I didn’t come to anything, I also surfed the forums with the same result. The main problem is this: I have a JSON document:

{
"devices": [
    {
        "name": "some name",
        "price": 2000,
        "year": 2022
    }
]
}

I use the following code to read the information:

//open my JSON
QFile file("path/to/myfile.json");
file.open(QIODevice::ReadOnly);
QByteArray jsonData = file.readAll();

//finding array
QJsonDocument document = QJsonDocument::fromJson(jsonData);
QJsonObject object = document.object();
QJsonArray temp_array = object["devices"].toArray();

//reading
qDebug() << temp_array[0].toObject().value("name").toString();  //returned ""
qDebug() << temp_array.size(); //returned 0
qDebug() << temp_array.empty(); //returned true
qDebug() << object.keys(); //returned QList("devices")

As I previously pointed out in a comment, trying to read the values of the "name" key returned me an empty string, the size and empty functions indicate that I'm looking at an empty array. However, the keys function indicates that my json object still contains the "devices" key. What could be the problem? [1]: https://doc.qt.io/qt-5/qtcore-serialization-savegame-example.html

like image 418
nyar Avatar asked Apr 29 '26 23:04

nyar


1 Answers

Your code seems to be doing correct things in correct order but something goes wrong. Either your file is not found or it doesn't get opened, or it is found but parsing fails.

You would find out if you did some checks instead of just assuming things work.

Below you will find example of robust programming. The example code checks

  • if file exists
  • if file opening fails
  • if file parsing to JSON fails
  • if file is actually JSON object (and not e.g. JSON array)
  • if size of the JSON array named "devices" is bigger than zero
  • if object in JSON array contains "name" property
  • if "name" property type is string

(I didn't try to compile the code, but I'm sure you get the idea and figure out what went wrong. If you made this kind of code to a function you would either return or throw exception when things go wrong...)

QFile file("path/to/myfile.json");
if (!file.exists()) {
    qWarning() << "File doesn't exist";
}

if (!file.open(QIODevice::ReadOnly)) {
    qWarning() << "Couldn't open file";
}

QByteArray jsonData = file.readAll();

QJsonParseError parseError;
QJsonDocument document(QJsonDocument::fromJson(jsonData, &parseError));
if (parseError.error != QJsonParseError::NoError) {
    qWarning() << "Invalid json file. Parsing failed:" << parseError.error << parseError.errorString();
}

if (!document.isObject()) {
    qWarning() << "File is not JSON object!";
}

const QJsonObject &object = document.object();

QJsonArray temp_array = object["devices"].toArray();

if (temp_array.size() < 1) {
    qWarning() << "JSON array object count:" << temp_array.size();
}

QJsonObject jsonObj = temp_array[0].toObject();

if (jsonObj.contains("name")) {
    if (jsonObj["name"].isString()) {
        qDebug() << jsonObj["name"].toString();
    } else {
        qWarning() << "name" << "is not string!";
    }
} else {
    qWarning() << "Object in JSON array did not have" << "name";
}
like image 186
talamaki Avatar answered May 02 '26 12:05

talamaki