【问题标题】:make a tree form [{"id":1},{"id":2,"children":[{"id":3},{"id":4},{"id":5,"children":[{"id":6}]}]制作树形 [{"id":1},{"id":2,"children":[{"id":3},{"id":4},{"id":5,"children ":[{"id":6}]}]
【发布时间】:2013-03-14 12:02:16
【问题描述】:

我在javascript中有一个这样的字符串变量:

var tree='[{"id":1},{"id":2,"children":[{"id":3},{"id":4},{"id":5,"children"[{"id":6}]}]';
now i want to create a tree from this in which
# 1 and 2 will at same level
# 3 ,4 ,5 will be the sub nodes of 2.
# 6 will be the sub node of 5.

请帮助通过 javascript 或 jquery 制作树形此树变量。 变量。

【问题讨论】:

标签: javascript


【解决方案1】:

在我看来,这并不多。我发现了一些拼写错误,但除此之外,它是一个 JSON 结构。在第二个“孩子”之后缺少一个冒号,并且也缺少一些右括号。我删除了引号。

var tree = [{
      "id" : 1
    }, {
      "id" : 2,
      "children" : [{
          "id" : 3
        }, {
          "id" : 4
        }, {
          "id" : 5,
          "children" : [{ //missing colon
              "id" : 6
            } //missing bracket
          ] //missing bracket
        }
      ]
    }
  ];
  console.log(JSON.stringify(tree[0]));
  console.log(JSON.stringify(tree[1]));
  console.log(JSON.stringify(tree[1].children));

【讨论】:

    【解决方案2】:
    var tree='[{"id":1},{"id":2,"children":[{"id":3},{"id":4},{"id":5,"children"[{"id":6}]}]';
    var objTree = JSON.parse(tree);
    
    console.log(objTree);
    

    请注意,您有几个拼写错误 - 找到它们,获取您的字符串,然后将其放入解析器 http://jsonlint.com

    【讨论】:

      【解决方案3】:

      有一些错字,请参阅评论。 无论如何,你只需要使用JSON.parse进行转换

      var tree='[{"id":1},{"id":2,"children":[{"id":3},{"id":4},{"id":5,"children":[{"id":6}]}]}]'; 
      //Missing ':' near 'children' and '}]' at the end
      
      var array = JSON.parse(tree);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-10-23
        • 1970-01-01
        • 2022-09-23
        • 2014-10-08
        • 2015-01-21
        • 1970-01-01
        • 1970-01-01
        • 2011-04-22
        相关资源
        最近更新 更多