【问题标题】:Parsed elements coming up as undefined解析的元素出现未定义
【发布时间】:2014-04-10 23:25:03
【问题描述】:

我正在尝试解析以下 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 在控制台中通过,但我尝试解析的字段显示为未定义。谁能告诉我我做错了什么?

【问题讨论】:

  • customer 是数组中对象的索引。该对象作为第二个参数传递。请参阅文档:api.jquery.com/jQuery.each。将console.log(customer) 放入回调中有助于调试问题。
  • console.log(this.name)console.log(this.cars)

标签: javascript jquery json parsing


【解决方案1】:

我认为这里的问题是您对$.each 的使用,您的回调函数将接收索引作为第一个参数,将值作为第二个参数,看起来您期望第一个参数是值。因此,在您当前的代码中,customer 将是一个索引(01 等),而不是 JSON 中的对象。

尝试将您的 $.each 呼叫更改为以下内容:

$.each(json.customers, function(index, customer) {
    console.log(customer.name);
    console.log(customer.cars);     
});

【讨论】:

    猜你喜欢
    • 2018-03-15
    • 2018-02-12
    • 1970-01-01
    • 2019-05-08
    • 2017-08-05
    • 2020-10-04
    • 1970-01-01
    • 2018-10-27
    • 2014-11-16
    相关资源
    最近更新 更多