vendredi 25 août 2017

C++ create json file from tree data structure

I have a small tree and I want to create a json file from it.

    1
  / | \
 /  |  \    
2   3   4
   / \     
  /   \
 5     6

where "1" is the root node that has "2", "3" and "4" as children. "3" has two children ("5" and "6") as well.

I want to create the following json output

{
    "Id": 1,
    "Child": [
        {
            "Id": 2
        },
        {
            "Id": 3,
            "Child": [
                {
                  "Id" : 5
                },
                {
                  "Id" : 6
                }
            ]
        },
        {
            "Id": 4
        }
    ]
}

here each "node" has an id and an array of (zero or more) children.

The code so far used as a driver is the following:

#include <iostream>
#include <string>
#include <vector>
#include "json.hpp"

using json = nlohmann::json;

int main( int argc, char** argv) {


   std::vector<int> vec = { 1, 2, 3, 5, 6, 4};

    json j;

    int depth = 1;

    for( int i = 0; i < vec.size(); i++) {

        if ( depth == vec[i] ) {

            j["id"] = vec[i];

        } else {


        }

    }

    std::cout << j.dump() << std::endl;

    return 0;

}

I am using http://ift.tt/1D7fWFV to create the json structure. I don't know how to recursively create the children. Any help?

Aucun commentaire:

Enregistrer un commentaire