简体   繁体   中英

Reading JSON tree structure into custom javascript object

I have a JSON string:

{ "a1": "root", 
  "a2": "root data", 
  "children": [
    { "a1": "child 1", 
      "a2": "child 1 data", 
      "children": []
    }, 
    { "a1": "child 2", 
      "a2": "child 2 data", 
      "children": [
        { "a1": "child 3", 
          "a2": "child 3 data", 
          "children": []
        }
      ]
    }
  ]
}

I want to read this JSON tree structured string into a JavaScript object. I want the class definition of the JavaScript object to be as follows:

function MyNode(){
    this.a1 = ""
    this.a2 = ""
    this.children = []
}

Basically after reading the JSON data structure I would like a have an instance of type MyNode which has the parameters a1 a2 and children , where children or the root node has instances of type MyNode and with data/parameters as specified in the JSON string.

How can I accomplish this? Any pointers would be very helpful.

First call JSON.parse on that string, then call a recursive function which will create a tree with use of your constructor.


Update:

  var output = parse_constructor(json);
    console.log(output);

    function parse_constructor(input){

       var output = new MyNode();
       output.a1 = input.a1;
       output.a2 = input.a2;

       for(var i in input.children){
           output.children.push(
               parse_constructor(input.children[i])
           );
       }
       return output;
    }

http://jsfiddle.net/zdeet6v5/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM