使用Javascript访问JSON对象内部的数组中的对象

11

我有一个编码的JSON对象,其中存储了一个对象数组,我希望循环遍历该数组并将其输入到数据库中。 Result对象类似于以下内容:

{
    "customers": [
        {
            "customer": {
                "id":"1",
                "customerName":"Customer Alpha",
                "customerID":" custA",
                "customerAddress":" Alpha Way",
                "customerCity":" Alpha",
                "customerState":" AL",
                "customerZip":"91605"
            }
        },
        {
            "customer": {
                "id":"2",
                "customerName":"Customer Beta",
                "customerID":" CustB",
                "customerAddress":" Beta Street",
                "customerCity":" Beta",
                "customerState":" BE",
                "customerZip":"91605"
            }
        }
    ]
}

我希望能够将每个字段输入到数据库中,但我目前使用的代码将未定义的内容输入到了数据库中。请问访问数组中存储的每个字段的变量的正确方法是什么?

下面是我目前使用的代码,但它不起作用:

function insertCustomer(customerName, customerID, customerAddress, customerCity, customerState, customerZip) {
db.transaction(function (tx) {
    tx.executeSql('INSERT INTO Customers (customerName, customerID, customerAddress, customerCity, customerState, customerZip) VALUES (?, ?, ?, ?, ?, ?)', [customerName, customerID, customerAddress, customerCity, customerState, customerZip], CountReturns);
    });
};

        $.ajax({
      url      : 'http://webserver/retrieveDatabase.php',
      dataType : 'json',
      type     : 'get',
      success  : function(Result){
        alert(Result.customers);
        for (var i = 0, len = Result.customers.length; i < len; ++i) {
          var customer = Result.customers[i];
          insertCustomer(customer.customerName, customer.customerID, customer.customerAddress, customer.customerCity, customer.customerState, customer.customerZip);
        }
      }
    });

警报会以一系列 [object Object] 的形式做出响应。


使用 console.log 代替 alert(并检查您的浏览器控制台以获取输出)。 Result.customers 是一个对象数组,这就是为什么alert显示您所看到的内容。 - bfavaretto
1
从您上面的示例数据来看,客户名称将通过以下方式访问:Result.customers[i].customer.customerName。但是您的代码仅使用了Result.customers[i].customerName。临时变量customer的名称隐藏了这种微妙之处。 - Jim Cote
@JimCote,你的回答不是一个“答案”,所以我不能把它顶上去,但经过三天的苦思冥想,你的评论救了我! - BillyNair
2个回答

10

修改

var customer = Result.customers[i];

为了

var customer = Result.customers[i].customer;

1

您可以像处理 JSON 对象一样处理:

for(var key in Result["customers"]) {
   // examples
   console.log( Result[key].customer );
   console.log( Result[key]["customer"] );
   console.log( Result[key]["customer"].customerID );
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接