QJsonDocument: How to replace a single object / or add it if it doesn't exists?
Hi there,
lets say there is a JSON file with more than 100 objects, build with QJsonObject, QJsonDocument and QFile:
{
"object1": {
"name": "whatever",
"size": "1"
},
"object6": {
"name": "whatever",
"size": "1"
}
"object23": {
"name": "whatever",
"size": "1"
}
and so forth...
}
With Qt 5.6 what's the easiest way to replace a single object (for example "object6") / or insert one if it doesn't exist (for example "object4")?
I got no problem to write the hole JSON file with a replaced or inserted new object again. But is it possible to just write / replace a single object?
Re: QJsonDocument: How to replace a single object / or add it if it doesn't exists?
You are manipulating a memory representation of the information in the file that you can then write to a file if you choose. You read the whole file into that structure, and write a whole file from that structure.
For your example document:
- Load the JSON text from a file into a QJsonDocument
- Get a copy of the outer QJsonObject from the document
- Use QJsonObject::remove() and QJsonObject::insert() to manipulate the QJsonObject
- Construct a new QJsonDocument from the modified QJsonObject
- Convert the document to JSON and save to a file
Re: QJsonDocument: How to replace a single object / or add it if it doesn't exists?
Hi Chris,
thank you for your help. I did have a look at QJsonObject::insert() before. But can this function really insert / overwrite a whole JSON Object? It seamed to me it is only capable to insert a single key/value pair inside an object?
Re: QJsonDocument: How to replace a single object / or add it if it doesn't exists?
Yes, they insert() or remove() single key/value pairs from a QJsonObject. Your example document is a single JSON object containing three key/value pairs where each value is another JSON object. You asked abput inserting a new "object4" key and removing "object6" key from that single object.
Re: QJsonDocument: How to replace a single object / or add it if it doesn't exists?
Hi Chris,
sorry I missunderstood the key/value parameter of 'insert(const QString &key, const QJsonValue &value)'. I thought it means you only can insert key / value pairs like "size" : "1" in the example above. And overlooked that the parameter 'value' also can be a whole JSON object.
Now it works. Thanks for helping!