creating nested json object in c++ using nlohmann json creating nested json object in c++ using nlohmann json json json

creating nested json object in c++ using nlohmann json


In order to serialize your own type, you need to implement a to_json function for that type.

#include <iostream>#include <string>#include <vector>#include "json.hpp"using namespace std;using json = nlohmann::json;struct json_node_t {    int id;    std::vector<json_node_t> child;};void to_json(json& j, const json_node_t& node) {    j = {{"ID", node.id}};    if (!node.child.empty())        j.push_back({"children", node.child});}int main() {    json_node_t node = {1, {{2, {}}, {3, {{5, {}}, {6, {}}}}, {4, {}}}};    json j = node;    cout << j.dump(2) << endl;    return 0;}

Output:

{  "ID": 1,  "children": [    {      "ID": 2    },    {      "ID": 3,      "children": [        {          "ID": 5        },        {          "ID": 6        }      ]    },    {      "ID": 4    }  ]}

A couple of more ways to initialize json_node_t (all producing the same tree and the same output):

struct json_node_t {    int id;    std::vector<json_node_t> child;    json_node_t(int node_id, initializer_list<json_node_t> node_children = initializer_list<json_node_t>());    json_node_t& add(const json_node_t& node);    json_node_t& add(const initializer_list<json_node_t>& nodes);};json_node_t::json_node_t(int node_id, initializer_list<json_node_t> node_children) : id(node_id), child(node_children) {}json_node_t& json_node_t::add(const json_node_t& node) {    child.push_back(node);    return child.back();}json_node_t& json_node_t::add(const initializer_list<json_node_t>& nodes) {    child.insert(child.end(), nodes);    return child.back();}int main() {    json_node_t node_a = {1, {{2, {}}, {3, {{5, {}}, {6, {}}}}, {4, {}}}};    json_node_t node_b = {1, {2, {3, {5, 6}}, 4}};    json_node_t node_c(1);    node_c.add(2);    node_c.add(3).add({5, 6});    node_c.add(4);    cout << json(node_a).dump(2) << endl << endl;    cout << json(node_b).dump(2) << endl << endl;    cout << json(node_c).dump(2) << endl;    return 0;}