Modifying an QJsonArray within a QJsonObject?

626 Views Asked by At

How to modify an array which is already inside a QJsonObject structure?

QJsonObject data = QJsonDocument::fromJson(QByteArrayLiteral("{\"array\":[1,2,3]}")).object();

// TODO: Something to append numbers to the 1,2,3 array?

// This doesn't work: 
data["array"].toArray().append(4);

qInfo() << data; // QJsonObject({"array":[1,2,3]}), without the 4th element

toArray() seems to create a copy instead of returning a reference

1

There are 1 best solutions below

0
On

I believe the problem is that toArray() is returning a copy of the array, not a reference to the existing array. So your code is attempting to modify the copy, and that ultimately has no effect. You should be able to do something like this instead:

QJsonArray arrayCopy = data["array"].toArray();
arrayCopy.append(4);
data["array"] = arrayCopy;