Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Change values in a json file



  • Hi!
    The only way I found is to read the file, change its contents and write back the whole file. I.e.:

    @ QFile file("filename.json");
    file.open(QIODevice::ReadOnly);
    QByteArray json = file.readAll();
    file.close();
    QJsonDocument doc(QJsonDocument::fromJson(json));
    QJsonObject root(doc.object());
    // change something
    doc.setObject(root);
    file.open(QIODevice::WriteOnly);
    file.write(doc.toJson(QJsonDocument::Indented));
    file.close();
    @

    Is this the recommended way?


  • Moderators

    Hi,

    [quote author="Mark" date="1424095290"]
    The only way I found is to read the file, change its contents and write back the whole file.

    ...

    Is this the recommended way?[/quote]Yes. There's no other way. (But you could store a copy of the contents, so that you don't have to read from the file every time you want to update it)


Log in to reply