Page 1 of 1

Accessing json encoded array

Posted: Tue Oct 23, 2012 7:20 am
by barb woolums
I using a jquery post to access a php script like so

Code: Select all

$.post("http://webrecipemanager.com/wrm_app/parseing.php", inData, function(data) {
....
});
the data returned is

{"ings":[{"ing":"","aisle":false,"item":"2 Percent Milk"},{"ing":"almond","aisle":"Nut & Seeds","item":"almond"}]}

but when I try to access data.ings it is undefined. What am I doing wrong?

Re: Accessing json encoded array

Posted: Tue Oct 23, 2012 7:42 am
by Christopher

Code: Select all

var myObject = JSON.parse(data);

Re: Accessing json encoded array

Posted: Tue Oct 23, 2012 3:41 pm
by requinix
You can also tell $.post that the data is JSON (which it normally would have detected but for some reason didn't) and jQuery will parse it for you.

Re: Accessing json encoded array

Posted: Tue Oct 23, 2012 4:43 pm
by barb woolums
Beautiful - al working now - thanks

Re: Accessing json encoded array

Posted: Tue Oct 30, 2012 6:27 pm
by barb woolums
Same scenario as above, but I'm using a rest service this time.

I can see the response in firebug:

{"ings":[{"item":"2\/3 c Sugar","ing":"Sugar","aisle":"Baking Goods"},{"item":"1 ts Vanilla","ing":"Vanilla","aisle":"Baking Goods"},{"item":"2\/3 c Raisins","ing":"Raisins","aisle":"Dried Fruit"},{"item":"2 Sheet Pastry","ing":"Sheet Pastry","aisle":"Frozen"},{"item":"1 c Walnuts","ing":"Walnuts","aisle":"Nuts & Seeds"},{"item":"5 md Egg","ing":"Egg","aisle":null},{"item":"5 tb Butter","ing":"Butter","aisle":null}]}

But when I alert(data) I get

[object Object]

and can't access the data. If I JSON.parse(data) I get a syntax error

JSON.parse: unexpected character

Re: Accessing json encoded array

Posted: Wed Oct 31, 2012 5:22 pm
by requinix
data is already an object - guess you don't have to JSON.parse() it.

Try console.log(data) or console.dir(data) to see what's in the object. Or even before that, try alert(data.ings[0].item).

Re: Accessing json encoded array

Posted: Wed Oct 31, 2012 6:39 pm
by barb woolums
Thanks, got it now.