27

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

Example

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 (probably with push) but I am having problems too.

Someone has idea how to do it?

1
  • Probably because you've got objects in objects and it's going to be arr[0][0].name Commented Jan 8, 2019 at 11:30

6 Answers 6

62

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Why should another layer be added. Also there is explanation of what was wrong with the JSON from the question. Please explain what you did find wrong.
18

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.

1 Comment

To be clear, if I paste your code exactly and go into jsfiddle and add this: alert(pets[0].name); it is undefined. forEach doesn't work either.
14

A simpler JSON array (an array of strings):

["jack", "john", "joe"];

Putting it together as JavaScript:

var pets = '["jack", "john", "joe"]';
var arr = JSON.parse(pets);
console.log(arr[0]); // jack
console.log(arr[1]); // john
console.log(arr[2]); // joe

Comments

8

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);

Comments

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

var arr = JSON.parse(pets);

alert(arr[0].name);

2 Comments

Please supply an explanation with your code. code only answers are discouraged.
Downvoted because this is obviously a simple copy of @amir-magdy answer.
-1

An Array must always be written inbetween square brackets

pets = [{"name":"jack"},{"name":"john"},{name:"joe"}];
var arr = JSON.parse(pets);
alert(arr[0].name);

2 Comments

How is this different from earlier answers?
Downvoted because this is obviously a simple copy of @amir-magdy answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.