Search code examples
c++jsonnlohmann-json

Json data creation for nlohmann


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?


Solution

  • 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"}};