【问题标题】:Reading JSON tree structure into custom javascript object将 JSON 树结构读入自定义 javascript 对象
【发布时间】:2015-07-28 21:25:11
【问题描述】:

我有一个 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 或根节点具有 @ 类型的实例987654328@ 和 JSON 字符串中指定的数据/参数。

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

【问题讨论】:

    标签: javascript json tree


    【解决方案1】:

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

    【讨论】:

    • 这是迄今为止最好的答案,但不是很多。如果你不打算演示如何编写函数的细节,最好作为评论。
    • @sitnarf 我只是要修改您的原始答案,因为递归一开始就失败了。您的新答案正常工作。谢谢。
    • 谢谢。很好的答案。奇迹般有效。 :-)
    猜你喜欢
    • 1970-01-01
    • 2019-08-20
    • 2014-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-27
    • 2019-12-24
    • 1970-01-01
    相关资源
    最近更新 更多