Search code examples
c++jsonnlohmann-json

Writing to a JSON file using c++?


Suppose I have a JSON object as follows :

{
    "Tickets": [
        {
            "Name" : "Alice Parker",
            "Age" : "21",
        }
    ]
}

The above text is from a Names.json file. I want to append more objects into Tickets Array. Suppose I have another Object as follows:

{
    "Name" : "Tony Stark",
    "Age" : "21",
}

I want to add this object also in the array. How can I to it and save the file.. The resultant File should now look like this -

{
    "Tickets": [
        {
            "Name" : "Alice Parker",
            "Age" : "21",
        },
        {
            "Name" : "Tony Stark",
            "Age" : "21",
        }
    ]
}

I am using This Package to use JSON in C++

how can I add more objects in the array and save it to a File called Names.json

My code so far:

std::ofstream output_file("TESTING.json");
json out;
out["Tickets"] = NAMES;
output_file << out.dump(4);
output_file.close();

I printed "NAMES" and it looks like this.

[
    {
        "Name" : "Alice Parker",
        "Age" : "21",
    },
    {
        "Name" : "Tony Stark",
        "Age" : "21",
    }
]

Solution

  • Looking at the documentation here, something like:

    json theData;
    // read from file to theData
    theData["Tickets"] += R("
    {
        "Name" : "Tony Stark",
        "Age" : "21",
    }
    )"_json;
    
    // or .push_back()
    

    Might work. Without sample code, though, I cannot test.