0

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 –

Kev
  • 118,037
  • 53
  • 300
  • 385
Tyler Evans
  • 567
  • 1
  • 8
  • 25

2 Answers2

3

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

Sushanth --
  • 55,259
  • 9
  • 66
  • 105
0

Don't use jQuery, just use JSON.parse(). Then, get it using obj.survey.id.

var obj = JSON.parse(userbookingstring);
alert(obj[0].survey.id);
saml
  • 6,702
  • 1
  • 34
  • 30
  • Why does he have to use `JSON.parse()`? Seems to already be JSON? – Explosion Pills Oct 01 '12 at 21:09
  • Hi, 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 – Tyler Evans Oct 01 '12 at 21:11
  • JavaScript is case-sensitive. 'obj.Survey' is not defined, 'obj.survey' is. – saml Oct 01 '12 at 21:12
  • still i get the same error:/ Uncaught TypeError: Cannot read property 'id' of undefined – Tyler Evans Oct 01 '12 at 21:13
  • Also, why are you using JSON.parse(JSON.stringify(userbooking))? That takes an Object, converts it to a JSON string, then converts it back to and Object. That's unnecessary. – saml Oct 01 '12 at 21:14
  • obj is an Array. you need to access the first element using: obj[0].survey.id – saml Oct 01 '12 at 21:16