Accessing json encoded array

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
barb woolums
Forum Contributor
Posts: 134
Joined: Sun Feb 08, 2009 9:52 pm

Accessing json encoded array

Post 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?
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Accessing json encoded array

Post by Christopher »

Code: Select all

var myObject = JSON.parse(data);
(#10850)
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Accessing json encoded array

Post 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.
User avatar
barb woolums
Forum Contributor
Posts: 134
Joined: Sun Feb 08, 2009 9:52 pm

Re: Accessing json encoded array

Post by barb woolums »

Beautiful - al working now - thanks
User avatar
barb woolums
Forum Contributor
Posts: 134
Joined: Sun Feb 08, 2009 9:52 pm

Re: Accessing json encoded array

Post 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
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Accessing json encoded array

Post 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).
User avatar
barb woolums
Forum Contributor
Posts: 134
Joined: Sun Feb 08, 2009 9:52 pm

Re: Accessing json encoded array

Post by barb woolums »

Thanks, got it now.
Post Reply