【发布时间】:2022-01-17 03:07:41
【问题描述】:
我希望能够将一个字符串解析为一个 JSON 对象,类似这样(文本可以是任何东西,我只是把它们这样放置以便您可以看到结构):
A
A-A
A-B
A-B-A
A-B-B
A-C
A-C-A
B
放入一个json对象,结构如下:
[
{
"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": [] }
]
到目前为止,我有以下内容,但我不确定这是否是最好的方法。也许递归方法会更好?
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)
【问题讨论】:
-
如果你不介意使用库,在 npm 上搜索会发现这个包:indent-tree。
-
@David784 虽然看起来确实不错,但我这样做是为了一个个人项目,并希望扩展我对这个主题的了解。如果这个没有引起太多关注,我会使用它!
-
完全理解。该项目的源代码在 github 上是公开的,here...它很短,而且代码看起来很可读。可能是一个很好的资源......
标签: javascript json parsing indentation