I have the following JSON object in javascript returned by a PHP web service :

data={
"result": "pass",
"error_type": "",
"feedback_ids": {
    "feedback0": "1",
    "feedback1": "8"
},
"redirect_uri": ""
}

alert(data.result) works like a peach. How do I access "feedback_ids" and alert feedback0 and feedback1?

share|improve this question
may be u havent parsed the JSON. Parse the JSON and then try it . var parsedObj = JSON.parse(data) ; alert(parsedObj.result); – user844866 Mar 5 at 19:49

4 Answers

up vote 1 down vote accepted

To access those variables you need to do:

data.feedback_ids.feedback0

and

data.feedback_ids.feedback1

If you have flexibility on server, make your life easier by changing that to JSON Array so you could loop them by their index. Note below I just changed the feedback_ids to the array structure

data={
"result": "pass",
"error_type": "",
"feedback_ids": [
    "1",
    "8"
],
"redirect_uri": ""
}
share|improve this answer
Hey Momo. I started with that! But everytime I alert it I am getting "undefined" as the result!! – sniper Aug 31 '11 at 3:57
Did you try data.feedback_ids[0]? – momo Aug 31 '11 at 4:00
I tried with the code I had as well as format you provided. Its still undefined. – sniper Aug 31 '11 at 4:02
This is the callback function from PHP : catch_merchant_feedback({"result":"pass","error_type":"","feedback_ids":["1","8"‌​],"redirect_uri":""}) – sniper Aug 31 '11 at 4:04
Hmmm, I just tried that in Firebug Console and it worked. Have you tried loading the page with Firebug and just output it in the console to see what kind of JSON structure you are getting? If possible, maybe post the client' side code as well – momo Aug 31 '11 at 4:07
show 3 more comments

To get at the feedback_ids:

ids = data.feedback_ids;

And to get inside that:

one   = data.feedback_ids.feedback0;
eight = data.feedback_ids.feedback1;

You could also use array notation:

one = data['feedback_ids']['feedback0'];
share|improve this answer
I am getting "undefined" when I try to alert the data. What am I doing wrong? I am very sure that the data is present! – sniper Aug 31 '11 at 3:55

data.feedback_ids.feedback0 and data.feedback_ids.feedback1

share|improve this answer
for (var k in data.feedback_ids) {
    console.log(k, data.feedback_ids[k]); 
}

This code will output:

feedback0, 1
feedback1, 8
share|improve this answer

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.