我试图解析以下JSON:
{
"customers": [
{ "name":"joe" , "cars":[
{"name":"honda","visits":[
{"date":"01/30/14","Id":"201"},
{"date":"01/30/14","Id":"201"},
{"date":"02/12/14","Id":"109"}
]},
{"name":"Nissan","visits":[
{"date":"01/30/14","Id":"201"},
{"date":"02/12/14","Id":"109"}
]}
]},
{ "name":"bob" , "cars":[
{"name":"escalade","visits":[
{"date":"01/05/14","Id":"301"},
{"date":"01/18/14","Id":"551"}
]},
{"name":"corvette","visits":[
{"date":"01/05/14","Id":"301"},
{"date":"01/18/14","Id":"551"}
]}
]}
]
}
使用以下jQuery脚本:
$("document").ready(function(){
$.getJSON("data1.json", function(json) {
console.log(json); // this will show the info it in firebug console
$.each(json.customers,function(customer){
console.log(customer.name);
console.log(customer.cars);
});
});
});
JSON正在控制台中传出,但我试图解析的字段是未定义的。谁能告诉我我做错了什么?
答案 0 :(得分:0)
我认为这里的问题是你使用$.each
,你的回调函数将接收索引作为第一个参数,值作为第二个参数,看起来你期望第一个参数是值。因此,在您当前的代码中customer
将是一个索引(0
,1
等),而不是来自JSON的对象。
尝试将$.each
来电更改为以下内容:
$.each(json.customers, function(index, customer) {
console.log(customer.name);
console.log(customer.cars);
});