将JSON树结构读入自定义javascript对象
我有一个JSON字符串:将JSON树结构读入自定义javascript对象,javascript,json,tree,Javascript,Json,Tree,我有一个JSON字符串: { "a1": "root", "a2": "root data", "children": [ { "a1": "child 1", "a2": "child 1 data", "children": [] }, { "a1": "child 2", "a2": "child 2 data", "children": [ { "a1": "child 3",
{ "a1": "root",
"a2": "root data",
"children": [
{ "a1": "child 1",
"a2": "child 1 data",
"children": []
},
{ "a1": "child 2",
"a2": "child 2 data",
"children": [
{ "a1": "child 3",
"a2": "child 3 data",
"children": []
}
]
}
]
}
我想将这个JSON树结构字符串读入JavaScript对象。我希望JavaScript对象的类定义如下:
function MyNode(){
this.a1 = ""
this.a2 = ""
this.children = []
}
基本上,在阅读了JSON数据结构之后,我希望有一个类型为MyNode
的实例,该实例具有参数a1
a2
和子节点
,其中子节点
或根节点具有类型为MyNode
的实例,并且具有JSON字符串中指定的数据/参数
我怎样才能做到这一点?任何指针都会非常有用。首先对该字符串调用JSON.parse,然后调用递归函数,该函数将使用构造函数创建树
更新:
var output = parse_constructor(json);
console.log(output);
function parse_constructor(input){
var output = new MyNode();
output.a1 = input.a1;
output.a2 = input.a2;
for(var i in input.children){
output.children.push(
parse_constructor(input.children[i])
);
}
return output;
}
这是迄今为止最好的答案,但也不多。如果您不打算演示如何编写函数的细节,最好是作为注释。@sitnarf我只是想修改您的原始答案,因为递归一开始失败了。你的新答案正确。谢谢,谢谢。回答得很好。工作起来很有魅力。:-)