Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/462.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将JSON树结构读入自定义javascript对象_Javascript_Json_Tree - Fatal编程技术网

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

将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",

我有一个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
子节点
,其中
子节点
或根节点具有类型为
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我只是想修改您的原始答案,因为递归一开始失败了。你的新答案正确。谢谢,谢谢。回答得很好。工作起来很有魅力。:-)