2013-03-14 90 views
0

我有一个像这样在JavaScript字符串变量:树形[{“id”:1},{“id”:2,“children”:[{“id”:3},{“id”:4},{“id”:5,“孩子 “:[{” ID“:6}]}]

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的。 变量。

+0

你能更具体吗?一个'树'是一个'数据结构' - http://stackoverflow.com/questions/8640823/what-javascript-tree-data-structures-are-available。你究竟需要什么? – 2013-03-14 12:06:55

+0

你想从树上做树! – Diode 2013-03-14 12:09:36

回答

0

在我看来,它并没有太大的意义。我发现了一些拼写错误,但除此之外,它是一种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)); 
0
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

有几个错字,看到评论为了那个原因。 无论如何,你只需要转换使用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);