如何在JavaScript中将选项卡式树转换为JSON?

use*_*864 8 javascript algorithm jquery tabs json

我环顾四周寻找答案,但我认为这是一个奇怪的问题.我如何转换,作为使用间距选项卡的文本文件,这:

parent
    child
    child
parent
    child
        grandchild
        grandhcild
Run Code Online (Sandbox Code Playgroud)

{
"name" : "parent",
"children" : [
    {"name" : "child"},
    {"name" : "child"},
]
},
{
"name" : "parent",
"children" : [
    {
    "name" : "child",
    "children" : [
        {"name" : "grandchild"},
        {"name" : "grandchild"},
        {"name" : "grandchild"},
    ]
    },
]
}
Run Code Online (Sandbox Code Playgroud)

JSON可能并不完美,但希望我的观点清楚.

小智 6

我有同样的问题。这是解决方案:

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));
Run Code Online (Sandbox Code Playgroud)


JSu*_*uar -2

从选项卡树文本文件生成 JSON

下面的链接专门解决您的问题。您所需要做的就是更新代码,以便输出的格式符合您的要求。


制表符分隔符转为 JSON

其他帮助