0

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);
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
shane
  • 342
  • 1
  • 5
  • 28
  • Which library are you using? – Alecto Irene Perez Apr 08 '19 at 21:22
  • Yes jsoncpp I cannot find any other way to do this Ive search for hours @drescherjm – shane Apr 08 '19 at 21:24
  • 3
    I’d wager that pretty much every JSON library in existence only supports overriding the file, not doing in-place operation. In-place operations in a structured file simply don’t make much sense (in other words: it’s physically impossible). Any reason for not wanting to read the JSON file, edit the structure, and write it back? – Konrad Rudolph Apr 08 '19 at 21:28

1 Answers1

1

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

Alecto Irene Perez
  • 10,321
  • 23
  • 46