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?
-
Probably because you've got objects in objects and it's going to be arr[0][0].nameJames W– James W2019年01月08日 11:30:25 +00:00Commented Jan 8, 2019 at 11:30
6 Answers 6
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 Comment
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
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
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
pets = '[{"name":"jack"},{"name":"john"},{"name":"joe"}]';
var arr = JSON.parse(pets);
alert(arr[0].name);
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);