0

I have an array that keep the data in tree structure but I'd like to transform this data to json. This is the example of my data :

[Object]
   0: Object
      children: Array[1]
          0: Object
             children: Array[1]
                0: Object
                   children: Array[10]
                      0: Object
                         children: Array[6]
                         value: Object
                      1: Object
                      2: Object
                      3: Object
                      4: Object
                      5: Object
                      6: Object
                      7: Object
                      8: Object
                      9: Object
                      value: Object
                         Id: "00145E5BB2641EE284F811A7907757A3"
                         Parent: "00145E5BB2641EE284F811A7907737A3"
                         Ref: undefined
                         Text: "Functional Areas"
                         Type: "TWB"

Now I want to transform these array of data to Json. I tried JSON.stringify(myArray); but the format isn't correct. It destroys all structure of tree. Any ideas?

This is the code that give the result above.

function transformToStruct(xmlData, callback) {
    var data = xmlData.item;        
    var roots=[];
    var children = {};
    var arry=createStructure(data); 

  // find the top level nodes and hash the children based on parent
  for (var i = 0, len = arry.length; i < len; ++i) {
      var item = arry[i],
          p = item.Parent,
          target = [];

        if(p == rootId) {
            target = roots;
        } 
        else {              
            target = (children[p] || (children[p] = []));           
        }

        target.push({ value: item });
  }
  // function to recursively build the tree
  var findChildren = function(parent) {
      if (children[parent.value.Id]) {
          parent.children = children[parent.value.Id];
          for (var i = 0, len = parent.children.length; i < len; ++i) {
              findChildren(parent.children[i]);
          }
      }
  };

  // enumerate through to handle the case where there are multiple roots
  for (var i = 0, len = roots.length; i < len; ++i) {
      findChildren(roots[i]);
  }
//  var returnV = JSON.stringify(roots);
//  callback(returnV);
  callback(roots)
}

function createStructure(data) {
    var arry = [];
    $.each(data, function(i, val) {
        var parent = val["ParentId"]["#text"];
        var id = val["NodeId"]["#text"];
        var text = val["NodeText"]["#text"];
        var level = val["NodeLevel"]["#text"];
        var ref = val["RefObject"]["#text"];
        var type = (val["NodeType"]["#text"]).substring(0,3);
        if(level == "01")
            rootId = parent;
        var item = {"Id": id, "Text": text, "Parent": parent, "Type" : type, "Ref" : ref};
        arry[i] = item;
//      arry.push(item);        
    });
    console.log(arry)
    return arry;
}
4
  • maybe duplicate: stackoverflow.com/questions/10919965/… Commented May 14, 2013 at 15:49
  • Is this a copy and paste of your tree object? If so, you get the format isn't correct message cause it's not correct. Commented May 14, 2013 at 15:49
  • I would like to see the native JavaScript Code of your object or just print it to the console log and paste it over here. the above is pseudo code but the prob seems to be the real code. Commented May 14, 2013 at 15:50
  • @jhorton Yes, I copy my data. What do you mean that it's not correct. Commented May 14, 2013 at 15:51

1 Answer 1

1

JSON can encode ("stringify") a native JavaScript Object in to a string notation. It can reversely create an other instance of this object back from that notation.

Sample:

var myArray = new Array("a", "b", "c");
var jsonNotation = JSON.stringify(myArray);
console.log(jsonNotation);

will give:

[
 "a",
 "b",
 "c"
]

The code above

[Object]
   0: Object
      children: Array[1]

is not JavaScript.

Sign up to request clarification or add additional context in comments.

1 Comment

The data above was generated with jQuery.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.