Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt modifying a JSON file

Tags:

c++

json

qt

I need to be able to read in an existing JSON file, make modifications to it (such as replacing, removing and adding objects, arrays and key-value pairs), and then write the file out again.

I have am trying to read and write to a JSON file with these contents:

{
    "array": [
        {
            "name": "Channel",
            "default": 1

        },
        {
            "name": "Size",
            "default": 457
        }
    ]
}

I am reading the file in successfully, but failing to make any changes to it using the following code:

QFile File("/path/to/myfile.json");
File.open(QIODevice::ReadOnly | QIODevice::Text);

QJsonParseError JsonParseError;
QJsonDocument JsonDocument = QJsonDocument::fromJson(File.readAll(), &JsonParseError);

File.close();

QJsonObject RootObject = JsonDocument.object();
QJsonArray Array = RootObject.value("array").toArray();

QJsonObject ElementOneObject = Array.at(0).toObject();

ElementOneObject.insert("key", QJsonValue(QString("value")));
ElementOneObject.insert("name", QJsonValue(QString("David")));

File.open(QFile::WriteOnly | QFile::Text | QFile::Truncate);
File.write(JsonDocument.toJson());
File.close();

I am expecting to see the first element of the array to have a new name of "David" and a new key-value pair like "key" : "value". The contents of the file are identical after this code has run. I know the file has been written out, because the ordering of the key-value pairs has been changed to be ordered by the keys sorted into alphabetic order.

How do I get the file to refelct the changes I have tried to make?

like image 288
oggmonster Avatar asked Sep 11 '25 18:09

oggmonster


1 Answers

The reason the example in the question does not work is because JsonDocument.object(), RootObject.value("array").toArray() and Array.at(0).toObject() all return copies of the data, not references. There are two different ways to handle this.

1) After making you changes to the element, insert it into the copy of your array, then insert the array into the RootObject copy, then set the RootObject on the JsonDocument

Array.removeAt(0);
Array.insert(0, ElementOneObject);
RootObject.insert("array", Array);
JsonDocument.setObject(RootObject);

2) Use find() to get references to the objects/values you want to modify

QJsonObject RootObject = JsonDocument.object();
QJsonValueRef ArrayRef = RootObject.find("array").value();
QJsonArray Array = ArrayRef.toArray();

QJsonArray::iterator ArrayIterator = Array.begin();
QJsonValueRef ElementOneValueRef = ArrayIterator[0];

QJsonObject ElementOneObject = ElementOneValueRef.toObject();

// Make modifications to ElementOneObject

ElementOneValueRef = ElementOneObject;
ArrayRef = Array;
JsonDocument.setObject(RootObject);
like image 86
oggmonster Avatar answered Sep 14 '25 09:09

oggmonster