7

I want store my datas in JSON file like:

{ "plottingData": [ { "min": 17, "max": 35, "mean": 20 }, { "min": 7, "max": 35, "mean": 17 }, { "min": 8, "max": 50, "mean": 29 } ] } 

How can I create this struct? I used to QJsonObject but I couldn't add QJsonArray like this.

0

2 Answers 2

9

From Qt documentation:

QJsonArray plot_array; // use initializer list to construct QJsonObject auto data1 = QJsonObject( { qMakePair(QString("min"), QJsonValue(17)), qMakePair(QString("max"), QJsonValue(35)), qMakePair(QString("mean"), QJsonValue(20)) }); plot_array.push_back(QJsonValue(data1)); // Or use insert method to create your QJsonObject QString min_str("min"); QString max_str("max"); QString mean_str("mean"); for(auto item : your_collection) { QJsonObject item_data; item_data.insert(min_str, QJsonValue(item.min)); item_data.insert(max_str, QJsonValue(item.max)); item_data.insert(mean_str, QJsonValue(item.mean)); plot_array.push_back(QJsonValue(item_data)); } QJsonObject final_object; final_object.insert(QString("plottingData"), QJsonValue(plot_array)); 
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for reply but I have maybe 600 datas? is there any method for this like addData (int min, int max, int mean){..}?
@HafsaElifElalmış See my edit. note that I doesn't write it in a compiler to test, so it may have problem. but basic usage is like this. Also you can read QT docs for QJsonObject, QJsonArray and QJsonValue for more info and their usages.
5
 QJsonObject o1 { { "min", 17 }, { "max", 35 }, { "mean", 20 }, }; QJsonObject o2; o2 [ "min" ] = 7; o2 [ "max" ] = 35; o2 [ "mean"] = 17; QJsonArray arr; arr.append ( o1 ); arr.append ( o2 ); QJsonObject obj; obj [ "plottingData" ] = arr; //to see the JSON output QJsonDocument doc ( obj ); qDebug() << doc.toJson ( QJsonDocument::Compact ); // or QJsonDocument::Indented // output: "{\"plottingData\":[{\"max\":35,\"mean\":20,\"min\":17},{\"max\":35,\"mean\":17,\"min\":7}]}" 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.