Json data creation for nlohmann

Viewed 255

I have some data like

{
"GLOBAL DATA":
    {
    "FIRST": [
                {"BEGIN": "0", "END" : "100"}
             ],
    "SECOND":"SomeData",
    "THIRD":"SomeMoreData"
    }
}

I want to add more data to FIRST array. I tried creating the insertion data as follows

json v2 = {"BEGIN": "200","END" : "300"};

But this gives error

example1.cpp:34:23: error: expected '}' before ':' token json v2 = {"BEGIN": "200","END" : "300"};

What's the issue with my v2 data?

2 Answers

You could wrap the JSON data in a raw string literal and use the _json user-defined literal to parse it:

json v2 = R"({"BEGIN": "200", "END": "300"})"_json;

Or you could make it directly (without parsing), but using valid C++ syntax:

json v2 = {{"BEGIN", "200"}, {"END", "300"}};

analyze pretty much what you want to do:

this here:

{"BEGIN":"0","END":"100","MIDDLE":50}

is an object at index 0 in the hierarchy:

globalData.first

so you can do get the element at index 0 in the array and add a new key:value

std::string st = "{\"GLOBAL DATA\":{\"FIRST\": [{\"BEGIN\": \"0\", \"END\" : \"100\"}],\"SECOND\":\"SomeData\",\"THIRD\":\"SomeMoreData\"}}";
nlohmann::json second = nlohmann::json::parse(st);
second["GLOBAL DATA"]["FIRST"].at(0).push_back({"MIDDLE", 50});
std::cout << second.dump().c_str();

the output:

{"GLOBAL DATA":{"FIRST": [{"BEGIN":"0","END":"100","MIDDLE":50}],"SECOND":"SomeData","THIRD":"SomeMoreData"}}
Related