Al Mamun Al Mamun - 3 months ago 40
C++ Question

How to add child/nested element inside json using json11 library?

I want to build following json object using json11

{
"arrayOfData": [
8,
11,
2016
],
"objectOfData": [
{"day": "8"},
{"month": "11"},
{"year": "2016"}]
}


I want to add array of data, nested/child object inside json11 object.

Answer

json11 supports the following syntax for nested objects and arrays:

{
   { //notice one more { here

     "arrayOfData", Json::array {  //notice {
         8,
         11,
         2016
       }
   }, //close

   {  //open
      "objectOfData", Json::array {
           Json::object { {"day", "8"} },    //notice {{ and }}
           Json::object { {"month", "11"} },
           Json::object { {"year", "2016"} }
       }
   } //close
}

Well that looks clumsy with embedded comments and the details of nested structures. Lets zoom out and look at the general syntax — the bigger picture — without comments and details of the nested structures:

auto object = Json::object {
   { key1, value1 },
   { key2, value2 },
   { key3, value3 },
   { key4, Json::array { ... } },
   { key5, Json::object { {...}, {...}, ... } },
   { key6, value6}
};

Hope that helps.