我怎样才能正确使用javascript函数JSON.parse()?

时间:2015-08-10 01:35:32

标签: 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

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.

3 个答案:

答案 0 :(得分:0)

确保您的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 = '[{"Name":"John Ranniel","Age":"19","City":"Manila"},{"Emergency Contact":"09197875656","Relation":"Sister"}]';

var arr = JSON.parse(response);

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. 




答案 1 :(得分:0)

您正在尝试解析已经是JavaScript对象的内容,而不需要进行解析。您需要解析JSON字符串。这不是JSON字符串。这是一个JavaScript对象。

请考虑以下事项:

[1,2]

这会将数组,强制转换为字符串“1,2”。然后JSON.parse会阻塞"[object Object],[object Object]" ,因为它不属于有效的JSON字符串。

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

[

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

但是你说JSON.parse工作并导致<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script> 。换句话说,您输入JSON.parse的参数显然 是一个字符串,并且已正确解析。在这种情况下,警报将正常工作。

答案 2 :(得分:-1)

您的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.

演示:Link

这个JSON是数组,你可以直接使用:

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