首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >制作树形[{"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}]}]
EN

Stack Overflow用户
提问于 2013-03-14 20:02:17
回答 3查看 251关注 0票数 0

我在javascript中有一个字符串变量,如下所示:

代码语言: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从这个树变量中生成一个树。变量。

EN

回答 3

Stack Overflow用户

发布于 2013-03-14 20:35:01

在我看来,这没什么大不了的。我发现了一些拼写错误,但除此之外,它是一个JSON结构。在第二个“孩子”后面少了一个冒号,也少了一些右括号。我去掉了引号。

代码语言:javascript
复制
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));
票数 0
EN

Stack Overflow用户

发布于 2013-03-14 20:41:01

代码语言:javascript
复制
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的解析器中即可

票数 0
EN

Stack Overflow用户

发布于 2013-03-14 20:46:34

有几个打字错误,请看评论。无论如何,您只需使用JSON.parse进行转换

代码语言:javascript
复制
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);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15408730

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档