我环顾四周寻找答案,但我认为这是一个奇怪的问题。我如何转换,作为使用间距选项卡的文本文件,这:
parent
child
child
parent
child
grandchild
grandhcild
至
{
"name" : "parent",
"children" : [
{"name" : "child"},
{"name" : "child"},
]
},
{
"name" : "parent",
"children" : [
{
"name" : "child",
"children" : [
{"name" : "grandchild"},
{"name" : "grandchild"},
{"name" : "grandchild"},
]
},
]
}
JSON可能并不完美,但希望我的观点清楚。
我刚刚为tabdown标记语言实现了这个功能 - 它完全符合您的要求。 https://github.com/antyakushev/tabdown
用法非常简单:
var lines = data.toString().split('\n');
var tree = tabdown.parse(lines);
console.log(tree.toString());
您还可以使用node.js之外的解析函数,它不依赖于任何模块。
我有同样的问题。这是解决方案:
function node(title,lvl){
var children = [],
parent = null;
return {
title:title,
children:children,
lvl:()=>lvl==undefined?-1:lvl,
parent:()=>parent, //as a function to prevent circular reference when parse to JSON
setParent:p=>{parent=p},
appendChildren: function(c){
children.push(c);
c.setParent(this);
return this
},
}
}
function append_rec(prev,curr) {
if(typeof(curr)=='string'){ //in the recursive call it's a object
curr = curr.split(' ');//or tab (\t)
curr = node(curr.pop(),curr.length);
}
if(curr.lvl()>prev.lvl()){//curr is prev's child
prev.appendChildren(curr);
}else if(curr.lvl()<prev.lvl()){
append_rec(prev.parent(),curr) //recursive call to find the right parent level
}else{//curr is prev's sibling
prev.parent().appendChildren(curr);
}
return curr;
}
root = node('root');
var txt =
`parent
child
child
parent
child
grandchild
grandhcild`;
txt.toString().split('\n').reduce(append_rec,root);
console.log(JSON.stringify(root.children,null,3));
从选项卡树文本文件生成JSON
以下链接专门解决您的问题。您需要做的就是更新代码,以便根据您的要求格式化输出。
Tab分隔符到JSON
其他帮助