Simpanoz
Simpanoz

Reputation: 2859

Get value from json response

I have following JSON response received from server:

   {
    "msg": "S",
    "comments": {
        "iRecords": [{
            "id": "9",
            "bid": "1",
            "uid": "5",
            "comment": "This is # 009",
            "adate": "Tuesday, 5th April, 2011 11:15:05",
            "status": "1",
            "userid": "5",
            "username": "pavlos",
            "oauthprovider": "l",
            "profile_link": null
        }]
    }
  }

Iam using following javascript/jQuery to get values but it is showing nothing:

obj = jQuery.parseJSON(responseText);
alert(obj.comments.iRecords[adate]);

Note: alert(obj.msg); is working fine.

How can I get value of adate in Javascript.

Thanks in advance

Upvotes: 1

Views: 13978

Answers (3)

McStretch
McStretch

Reputation: 20675

iRecords holds an array of objects, so you need to access the first index of the array to get to the first object:

obj = jQuery.parseJSON(responseText); 
alert(obj.comments.iRecords[0]["adate"]);

or

alert(obj.comments.iRecords[0].adate);

Upvotes: 5

Quentin
Quentin

Reputation: 944256

You haven't defined a variable called adate and iRecords is an array

If you use square bracket notation then you have to pass in a string containing the property name, not a variable with the same name as the property.

obj.comments.iRecords[0].adate;

Upvotes: 5

Alex K.
Alex K.

Reputation: 175936

obj has a comments object which has an iRecods member which is an array with 1 element so;

x = obj.comments.iRecords[0].adate

Upvotes: 1

Related Questions