使用Javascript访问JSON对象内的Array内的对象

时间:2013-05-03 18:02:53

标签: javascript arrays json sqlite

我有一个编码的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);
        }
      }
    });

警报响应一系列[对象]。

2 个答案:

答案 0 :(得分:7)

更改

var customer = Result.customers[i];

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

答案 1 :(得分: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 );
}