javascript - 使用 Javascript 访问 JSON 对象中数组中的对象

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

警报以一系列 [object Object] 响应。

最佳答案

改变

var customer = Result.customers[i];

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

关于javascript - 使用 Javascript 访问 JSON 对象中数组中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16365029/

相关文章:

java - 在不使用 HashMap 的情况下查找排序的 ArrayList 中最常见的字符串

javascript - 更改 JSON 文件搜索结果的格式

javascript - 从对象中解析名称并显示 - Angular Js

json - 可以在 Grails 1.3.7 中漂亮地打印 JSON 吗?

javascript - 用新的 HTML 内容替换每个出现的单词

javascript - ASP.NET Web API Controller 更新行

arrays - 如何防止在matlab中创建结构体数组?

javascript - 将错误消息应用于文本框

javascript - 如何在包装 div 中启用 Froala 编辑器?

javascript - 使用 Angular 将 HTTP 数组值从服务导入到组件中