Search code examples
javascriptjqueryjsonbackbone.jscascading

Access Cascaded JSON in javascript


If I have the following JSON object, how can I access the survey.id (e.g 1) using JavaScript? I'm using Backbone / json.stringify / object.parse

[{
    "class": "org.example.UserBooking",
    "id": 1,
    "booking": {
        "class": "Booking",
        "id": 1
    },
    "profile": {
        "class": "Profile",
        "id": 3
    },
    "survey": {
        "class": "Survey",
        "id": 1
    },
    "tslot": {
        "class": "TimeSlot",
        "id": 5
    }
}]

??

I can't figure out how to access this "survey" id as its cascaded in. If I wanted to access the "id" for example i do:

var obj = $.parseJSON(JSON.stringify(userbooking));

alert(obj.id);

thanks


thanks for your response. When i try the following line:

var obj = JSON.parse(JSON.stringify(userbooking)); alert(obj.Survey.id);

i get the following error:

Uncaught TypeError: Cannot read property 'id' of undefined –


Solution

  • Try accessing the id inside survey like this

     obj[0].survery.id
    

    The json data in the current context is enclosed like this

    [ { } ]..

    So it's a array of objects , because it's the First object we are trying to access..

    It should be obj[0]. and not just obj.

    CHECK DEMO