|HELP| : How to extract Data from Json file ?
-
Hi and welcome to the forums.
You seem off to a good start.
What you have is a json array with objects in it.So in you for loop you will get QJsonObject and not a
QJsonValue if i read it correctly :=)
Nope. @JonB is right :) -
@Elmehdi said in |HELP| : How to extract Data from Json file ?:
I'm new to both Qt and Json
Just in case, have you read the documentation?
There's even a good example...
-
@Elmehdi
With all die respect to my learned friend @mrjj, you do getQJsonValue
s as you iterate throughQJsonArray jsonArray
.The point is, a
QJsonValue
can hold many data types (see https://doc.qt.io/qt-5/qjsonvalue.html#details). In your case those will beQJsonObject
s. The first thing you should write in your code is:foreach (const QJsonValue & value, jsonArray) { qDebug() << value.type(); }
and look at the values per https://doc.qt.io/qt-5/qjsonvalue.html#Type-enum.
From there, you will probably also want to look at
QJsonObject QJsonValue::toObject()
and/orQVariant QJsonValue::toVariant()
.If you know about recursion, that will be pretty handy when parsing JSON data.
-
Hi
I think what confused me is this
QJsonArray jsonArray = json_obj["cases"].toArray();
i dont see "cases" in the data sample. -
Thank you all. And a special thanks to @LeLev who helped me in private. apparently the base-ranged for loop helped me since it reconizes the type of objects that are stored in the QjsonArray so it access them all. This was what worked for me:
QFile countries_file("countries.json"); QFile morocco_file("morocco.json"); QString json_string; if(countries_file.open(QIODevice::ReadOnly | QIODevice::Text)){ json_string = countries_file.readAll(); countries_file.close(); } else qDebug()<< "file not found"; auto json_doc = QJsonDocument::fromJson(json_string.toUtf8()); QJsonArray jArr = json_doc.array(); QJsonValue val; for(auto jsonObj : jArr) { val = jsonObj.toObject().value("country"); _country = val.toString(); qDebug() << "Country: "<< _country; val = jsonObj.toObject().value("cases"); _cases = val.toInt(); qDebug() << "Cases: "<< _cases; val = jsonObj.toObject().value("deaths"); _deaths = val.toInt(); qDebug() << "Deaths: "<< _deaths; } qDebug() << Qt::endl; qDebug() << Qt::endl;