2

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.

1 Answer 1

4

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/

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

2 Comments

This is the best answer so far, but not by much. If you're not going to demonstrate the details of how to write the function, it would be better as a comment.
@sitnarf I was just going to modify your original answer because the recursion was failing at first. Your new answer works correctly. Thank you.

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.