如何正确使用javascript函数JSON.parse()?

如何正确使用javascript函数JSON.parse()?,javascript,arrays,json,Javascript,Arrays,Json,我有一个用JSON打印的数组 [{"Name":"John Ranniel","Age":"19","City":"Manila"},{"Contact":"09197875656","Relation":"Sister"}] 出于某种原因,我将JSON分为两部分 在javascript中,我使用JSON.parse来解码上面的JSON 例如: var arr = JSON.parse(response); //The response variable contains the above

我有一个用JSON打印的数组

[{"Name":"John Ranniel","Age":"19","City":"Manila"},{"Contact":"09197875656","Relation":"Sister"}]
出于某种原因,我将JSON分为两部分

在javascript中,我使用JSON.parse来解码上面的JSON

例如:

var arr = JSON.parse(response); //The response variable contains the above JSON

alert(arr[0].Name) //Still it outputs John Ranniel, but If i change the content of the alert box on the second part of the JSON,
alert(arr[1].Contact) // It has no output, I don't know if there is a problem with the index of the array.

确保JSON是字符串类型:

'[{"Name":"John Ranniel","Age":"19","City":"Manila"},{"Emergency Contact":"09197875656","Relation":"Sister"}]'
然后,你可以使用

var arr = JSON.parse(response); //The response variable contains the above JSON

console.log(arr[0].Name);
console.log(arr[1]['Emergency Contact']); // There is no 'Contact' property iun your object, and you should use this when there's a space in the name of the property. 
见:

var response=“[{姓名:约翰·兰尼尔,年龄:19岁,城市:马尼拉},{紧急联系人:09197875656,关系:姐妹}]”; var arr=JSON.parseresponse; console.logarr[0]。名称;
console.logarr[1][“紧急联系人];//对象中没有“Contact”属性,当属性名称中有空格时,应使用此属性 您的JSON结构是数组,必须解析为JSON,请使用JSON.stringify将其解析为JSON:

var json = [{"Name":"John Ranniel","Age":"19","City":"Manila"},{"Contact":"09197875656","Relation":"Sister"}];

var str = JSON.stringify(json);

console.log(json);

var arr = JSON.parse(str);
alert(arr[0].Name) //Still it outputs John Ranniel, but If i change the content of the alert box on the second part of the JSON,
alert(arr[1].Contact) // It has no output, I don't know if there is a problem with the index of the array.
演示:

此JSON为数组,您可以直接使用:

var json = [{"Name":"John Ranniel","Age":"19","City":"Manila"},{"Contact":"09197875656","Relation":"Sister"}];
alert(json[0].Name);
alert(json[1].Contact);

您正在尝试解析已经是JavaScript对象的东西,并且不需要解析。您需要解析JSON字符串。这不是JSON字符串。它是一个JavaScript对象

考虑以下几点:

JSON.parse([1,2])
这会将数组[1,2]强制为字符串1,2。然后,JSON.parse将阻塞、,因为它不属于有效的JSON字符串

在您的情况下,对象将被强制为字符串

"[object Object],[object Object]"
parse将接受前导[作为数组的开头,然后抛出以下字符o,因为它不属于正确的JSON字符串


但是您说JSON.parse起作用并导致arr。换句话说,您提供给JSON.parse的参数显然是一个字符串,并且被正确解析。在这种情况下,警报将正常工作。

PS:那里没有联系人属性。另外,您可能指的是arr[1][紧急联系人]?输入错误,这只是一个例子。这与我正在编写的代码不同。但它们有相同的问题。期望文本作为第一个参数,而不是数组。这是文本,它来自PHP的回声。为什么我要将其字符串化,然后立即解析它?只需使用原始对象即可。