[英]Reading JSON tree structure into custom javascript object
我有一个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",
"a2": "child 3 data",
"children": []
}
]
}
]
}
我想将这个JSON树结构化字符串读入JavaScript对象。 我希望JavaScript对象的类定义如下:
function MyNode(){
this.a1 = ""
this.a2 = ""
this.children = []
}
基本上在阅读JSON数据结构之后,我希望有一个MyNode
类型的实例,它具有参数a1
a2
和children
,其中children
节点或根节点具有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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.