简体   繁体   English

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

[英]Accessing Objects inside Array inside JSON object using Javascript

I have an encoded JSON object that stores an array of objects that I wish to iterate through in order to input into a database. 我有一个编码的JSON对象,它存储了我希望迭代的对象数组,以便输入到数据库中。 The Result object is similar to as follows: 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"
            }
        }
    ]
}

I'd like to be able to input each field into the database, but the code I have inputs undefined into the database for everything. 我希望能够将每个字段输入到数据库中,但是我输入的代码未定义到数据库中以用于所有内容。 What is the proper way to access the variables stored in each field inside the array? 访问存储在数组内每个字段中的变量的正确方法是什么?

Here's what I'm using so far which doesn't work: 这是我到目前为止使用的不起作用:

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);
        }
      }
    });

The alert responds with a series of [object Object]s. 警报响应一系列[对象]。

Change 更改

var customer = Result.customers[i];

to

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

You can handle the JSON object like: 您可以处理JSON对象,如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM