Skip to content Skip to sidebar Skip to footer

Make A Tree Form [{"id":1},{"id":2,"children":[{"id":3},{"id":4},{"id":5,"children":[{"id":6}]}]

i have a string variable in javascript like this: 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

Solution 1:

There is not much to it, in my opinion. I found some typos, but otherwise, it is a JSON structure. There was a colon missing after the second "children" and some closing brackets were missing too. And i removed the quotes.

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));

Solution 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);

Just a heads up that you have a couple of typos - to find them, take your string and just plop it into the parser at http://jsonlint.com


Solution 3:

There's a few typo, see the comment for that. Anyway, you just have to convert using 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);

Post a Comment for "Make A Tree Form [{"id":1},{"id":2,"children":[{"id":3},{"id":4},{"id":5,"children":[{"id":6}]}]"