Good day. In my QT aplication, there is a need to store the value of structures of the same type in a JSON dictionary. Values should be possible to add, read, change, delete. I know about the JSON Save Game Example article, 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: Let's say I have the following structure:
struct Laptop{
std::string name;
int price;
int year;
};
And I want to store an array of such structures in a JSON dictionary. I am using the following code:
//filling structure
Laptop Ltemp = {"some name" , 1000, 2022};
//adding structure to JSON object
QJsonObject g;
g.insert("name", Ltemp.name.c_str());
g.insert("price", Ltemp.price);
g.insert("year", Gtemp.year);
//open and wtritingmy JSON
QFile file("path/to/myfile.json");
QByteArray jsonData = file.readAll();
QJsonDocument document = QJsonDocument::fromJson(jsonData);
QJsonObject object = document.object();
QJsonValue value = object.value("mydata");
QJsonArray myArray= value.toArray();
myArray.removeAt(0);
myArray.append(g);
object.insert("mydata", myArray);
document.setObject(object);
//write to file
file.write(document.toJson());
file.close();
{
Expecting at the same time that when you re-apply the code, the data of the structure will be added to the same array, the key of which is "mydata", but in the end I have this:
"mydata": [
{
"name": "some name",
"price": 1000,
"year": 2022
}
],
"mydata": [
{
"name": "some name",
"price": 1000,
"year": 2022
}
]
}
instead of
"mydata": [
{
"name": "some name",
"price": 1000,
"year": 2022
},
{
"name": "some name",
"price": 1000,
"year": 2022
}
]