0

I need to create the following structure but I am struggling to do this using json.

{
    "ParentTree": [{
        "Name": "Name3",
        "children": [{
            "Name": "Name2",
            "children": [{
                "Name": "Name1",
                "children": [{
                    "Name": "Name0"
                }]
            }]
        }]
    }]
}

I have tried below but unable to get how to add name and children keys dynamically.

json jsonObj;
jsonObj["ParentTree"] = json::array();
for (auto index = 3; index >= 0; index--) {
    jsonObj["ParentTree"].push_back(json::object());
}

Previously it was done using below way without using nlohmann json:

std::string PResult = "\"ParentTree\":[{";
for (int j = 3; j >= 0; j--)
{
    std::string num = std::to_string(j);
    PResult += "\"Name\":\"";
    PResult += "Name";
    PResult +=  num + "\",";
    if (j == 0) break;
    PResult += "\"children\":[{";
}

PResult.erase(PResult.length() - 1);

for (int j = 3; j >= 0; j--)
{
    PResult += "}]";
}
Arun
  • 2,247
  • 3
  • 28
  • 51

1 Answers1

1

The following code constructs your desired json object.

The curly brackets might be confusing at first glance, but once you read the docs and have an idea on how json::array() & json::object() works, you should be able to understand. (Read the example code in the hyperlink above.)

#include "json.h"
#include <iostream>
using namespace nlohmann;

int main() {
  json jsonObj;
  jsonObj["ParentTree"] = json::array();

  // Bottom-up approach: construct inside object first.
  json child0 = json::array({json::object({{"Name", "Name0"}})});
  json child1 = json::array( {json::object({{"Name", "Name1"}, {"children", child0}})} );
  json child2 = json::array( {json::object({{"Name", "Name2"}, {"children", child1}})} );
  jsonObj["ParentTree"] = json::array( {json::object({{"Name", "Name3"}, {"children", child2}})} );

  std::cout << jsonObj.dump(2);
}
Pin-Yen
  • 319
  • 2
  • 7