Tab separeted tree to JSON

Viewed 132

How do I go around converting a tab-separated text tree like this:

a
    a1
        a3
    a2

into a JSON format tree like this:

[
{
    "name":"a",
    "children":[
        {
            "name":"a1",
            "children":[
                {
                    "name":"a3",
                    "children":[]
                }
            ]
        },
            {
                "name":"a2"
                "children":[]
            }
    ]
}
]

in javascript? I think that you get the idea, I want a tab \t separated tree structure to be converted into a JSON tree structure. Thanks!

1 Answers

You could split the data into lines and separate tabs for getting a level and the name.

To create a tree take an array of known levles and assign each new node to the level's array and to the next level.

var data = 'a\n\ta1\n\t\ta3\n\ta2',
    tree = [];
    levels = [tree];
    
data
    .split('\n')
    .forEach(s => {
        const [{ length: level }, name] = s.split(/([^\t]+)/);
        levels[level].push({ name, children: levels[level + 1] = [] });
    });

console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related