0

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

OJW
  • 4,514
  • 6
  • 40
  • 48

1 Answers1

1

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;
JarMan
  • 7,589
  • 1
  • 10
  • 25