Javascript,用动态内容阅读json的问题

时间:2013-12-29 21:49:00

标签: javascript json

我有一个像这样的json:

[
  {
    "Code": 100
  },
  {
    "Drivers": [
      {
        "RowID": "1",
        "DriverName": "ZZ",
        "DriverAlias": "FF",
        "DriverEmail": "YY@gmail.com",
        "DriverPhone": "1121112229"
      },
      {
        "RowID": "3",
        "DriverName": "OO",
        "DriverAlias": "EE",
        "DriverEmail": "kkk@gmail.com",
        "DriverPhone": "12121458474"
      }
    ]
  }
]

我在Javascript中读这样的json:

for (var i = 0; i < data.length; i++) {  
 Drivers[i] = {
  RowID: data[1].Drivers[i].RowID,
  DriverName: data[1].Drivers[i].DriverName,
  DriverAlias: data[1].Drivers[i].DriverAlias,
  DriverEmail: data[1].Drivers[i].DriverEmail,
  DriverPhone: data[1].Drivers[i].DriverPhone
 };
}

它正在工作但是当我的json只有一个这样的驱动程序时:

[
  {
    "Code": 100
  },
  {
    "Drivers": [
      {
        "RowID": "1",
        "DriverName": "ZZ",
        "DriverAlias": "FF",
        "DriverEmail": "YY@gmail.com",
        "DriverPhone": "1121112229"
      }
    ]
  }
]

它不起作用,我是以错误的方式阅读json吗?感谢。

2 个答案:

答案 0 :(得分:4)

试试这个 - 你需要检查数据的长度[1]。驱动程序:

for (var i = 0; i < data[1].Drivers.length; i++) {  
 Drivers[i] = {
  RowID: data[1].Drivers[i].RowID,
  DriverName: data[1].Drivers[i].DriverName,
  DriverAlias: data[1].Drivers[i].DriverAlias,
  DriverEmail: data[1].Drivers[i].DriverEmail,
  DriverPhone: data[1].Drivers[i].DriverPhone
 };
}

答案 1 :(得分:0)

您可以通过以下方式缩短代码:

var Drivers = [];
for (var i = 0; i < data[1].Drivers.length; i++) {  
    Drivers[i] = {};
    for (var j in data[1].Drivers[i]) {
        Drivers[i][j] = data[1].Drivers[i][j];
    }
}

它会自动遍历data[1].Drivers数组中的每个对象,并复制这些对象中的所有对象。这也会自动复制存储在json中的任何其他值。