我有一个 ajax 调用,它返回以下 JSON:
returnedData = "[
{ id: 1, firstName: 'John', lastName: 'Smith', address: '123 Spa Road', city: 'London',
orders:
[
{ product: 'TV', price: 599.99, quantity: 2, orderTotal: 1199.98 }
]
}
]";
var customers = JSON.parse (returnedData);
console.log(customers.length); // prints length of the string data
它将其视为字符串。但是,我直接分配结果。
var customers = [
{ id: 1, firstName: 'John', lastName: 'Smith', address: '123 Spa Road', city: 'London',
orders:
[
{ product: 'TV', price: 599.99, quantity: 2, orderTotal: 1199.98 }
]
}
];
console.log(customers.length); // prints 1 - the number of objects
为什么会这样?如何动态分配它?
最佳答案
通过 http://jsonlint.com/ 运行代码你会发现你的代码中有错误。
将对象文字粘贴到您将看到的验证器中
Parse error on line 2:
[ { id: 1, first
--------------^
Expecting 'STRING', '}'
您需要在名称和字符串值两边加上双引号。
关于javascript - JSON 对象被视为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20683838/