Search code examples
c++jsonjsoncpp

Write to existing json file


I am using this code to add to my existing JSON file. However It completely overrides my JSON file and just puts one JSON object in it when I would just like to add another item to the list of items in my JSON file. How would I fix this?

Json::Value root;
    root[h]["userM"] = m;
    root[h]["userT"] = t;
    root[h]["userF"] = f;
    root[h]["userH"] = h;
    root[h]["userD"] = d;

    Json::StreamWriterBuilder builder;
    std::unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter());
    std::ofstream outputFileStream("messages.json");
    writer-> write(root, &outputFileStream);

Solution

  • My recommendation is

    • Load the file into a Json::Value
    • Add or change whatever fields you want
    • Overwrite the original file with the updated Json::Value

    Doing this is going to be the least error-prone method, and it'll work quickly unless you have a very large Json file.

    How to read in the entire file

    This is pretty simple! We make the root, then just use the >> operator to read in the file.

    Json::Value readFile(std::istream& file) {
        Json::Value root;
        Json::Reader reader;
        bool parsingSuccessful = reader.parse( file, root );
        if(not parsingSuccessful) {
            // Handle error case
        }
        return root; 
    }
    

    See this documentation here for more information