Json Array Javascript

Json Array Javascript

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

6 Answers

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

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

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

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);
0
pets = '[{"name":"jack"},{"name":"john"},{"name":"joe"}]';

var arr = JSON.parse(pets);

alert(arr[0].name);
2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett
Author

Chloe Bennett

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.