I am using json_parse from

http://www.JSON.org/json_parse.js

I need to store 3 pet names in "string" format, parse them into array and later read one by one

for example like that:

pets = '{{"name":"jack"},{"name":"john"},{name:"joe"}}';

var arr = JSON.parse(pets);

alert(arr[0].name);

But it doesn't work.

Also I would need to add entry to array(proably with push) but I am having problems too.

Someone has idea how to do it?

share|improve this question

3 Answers

up vote 7 down vote accepted

Your JSON is malformed. Try this:

var pets = '{"pets":[{"name":"jack"},{"name":"john"},{"name":"joe"}]}';
var arr = JSON.parse(pets);
alert(arr.pets[0].name);
share|improve this answer
Thank you very much, wish I asked 2 hours ago(yep i was trying 2h lol) – Joe Doe Feb 23 '12 at 19:15

JSon arrays are bounded by [] brackets

try

pets = '[{"name":"jack"},{"name":"john"},{"name":"joe"}]';

also you forgot to use "'s on the last property name.

share|improve this answer
@Bradley - ty and I must admin I usually put the arrays inside a object as you have done, even if just as a first check on recieving JSon from an AJAX call, if (obj.pets) – Dampsquid Feb 23 '12 at 19:11

yes just change it to this square brackets also check the double quotations on the last element

pets = '[{"name":"jack"},{"name":"john"},{"name":"joe"}]';

var arr = JSON.parse(pets);

alert(arr[0].name);
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.