I’d like to be able to parse a string into a JSON Object, something like this (the text can be anything, I’m just putting them like this so you can see the structure):
A
A-A
A-B
A-B-A
A-B-B
A-C
A-C-A
B
into a json object, structured like this:
[
{
"root": "A",
"content": [
{ "root": "A-A", "content": [] },
{
"root": "A-B",
"content": [
{ "root": "A-B-A", "content": [] },
{ "root": "A-B-B", "content": [] }
]
},
{
"root": "A-C",
"content": [
{ "root": "A-C-A", "content": [] }
]
}
]
},
{ "root": "B", "content": [] }
]
So far, I have the following, but I’m not sure if this is the best way of doing it. Maybe a recursive approach would be better?
let body = [];
let indentStack = [0];
for (let line of input.split('n')) { // input is the string I'd like to parse
if (line.trim() == '') continue; // skips over empty lines
let indent = line.match(/^ +/);
indent = indent ? indent[0].length : 0; // matches the first group of spaces with regex, gets the indent level of this line
if (indentStack[indentStack.length-1] != indent)
if (indentStack.includes(indent)) indentStack.length = indentStack.indexOf(indent)+1; // remove all indent levels after it as it's returned back to a higher level
else stack.push(indent);
console.log(`${(indent + '[' + indentStack.join() + ']').padEnd(10, ' ')}: ${line}`); // debugging
if (indentStack.length == 1) body.push({ root: line, content: [] });
else {
body[body.length-1].content.push({ root: line.substring(indent), content: [] })
}
}
console.log(body)