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

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 对象的 class 定义如下:

function MyNode(){
    this.a1 = ""
    this.a2 = ""
    this.children = []
}

基本上在阅读 JSON 数据结构后,我想要一个 MyNode 类型的实例,它具有参数 a1 a2children ,其中 children 或根节点具有 MyNode 类型的实例,并具有 JSON 字符串中指定的 data/parameters。

我怎样才能做到这一点?任何指示都会非常有帮助。

首先对该字符串调用 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/