gpt4 book ai didi

javascript - 将 JSON 树结构读入自定义 javascript 对象

转载 作者:行者123 更新时间:2023-11-30 12:18:43 24 4
gpt4 key购买 nike

我有一个 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 a2children,其中 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;
}

http://jsfiddle.net/zdeet6v5/1/

关于javascript - 将 JSON 树结构读入自定义 javascript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31687390/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com