使用jQuery从没有标识符的JSON数组中选取第一个元素

3

我无法访问DATA数组中的数字,这个数字在COLUMNS中提到的是ID。

我的JSON数据如下:

{
  "COLUMNS": [
    "ID",
    "DESCRIPTION",
    "DATE"
  ],
  "DATA": [
    [
      53,
      "Try to do something test123",
      "September, 05 2017 00:00:00 +0100"
    ]
  ]
}

我当前的尝试是这样的,但是使用这种方法,我得到了整个3个元素

  var jsonLength= JSON.DATA.length;

  for (dataIndex = 0; dataIndex < jsonLength; dataIndex++) {

      var dataLength= JSON.DATA[dataIndex].length;

      for (noteIndex = 0; noteIndex < dataLength; noteIndex++) {

          alert(JSON.DATA[dataIndex]);

      }
  }

你尝试过这样写吗 DATA[0][0] - guradio
现在我要感谢Rory McCrossan的回答。 - Ruuji K. Hasegawa
2个回答

4

你的代码几乎正确,只是在二维数组 DATA 上缺少第二个索引访问器。你可以使用循环中的 noteIndex 自增变量:

var JSON = {
  "COLUMNS": [ "ID", "DESCRIPTION", "DATE" ],
  "DATA": [ 
    [ 53, "Try to do something test123", "September, 05 2017 00:00:00 +0100" ] 
  ]
}
var jsonLength = JSON.DATA.length;

for (dataIndex = 0; dataIndex < jsonLength; dataIndex++) {
  var dataLength = JSON.DATA[dataIndex].length;
  for (noteIndex = 0; noteIndex < dataLength; noteIndex++) {
    console.log(JSON.DATA[dataIndex][noteIndex]); // note the additional [] here
  }
}


2
 var jsonLength= JSON.DATA.length;

  for (var i = 0; i < jsonLength; i++) {

      var note = JSON.DATA[i]
      var id = note[0] // access id value

  }

此外,如果您是服务器的所有者,为什么不返回更适合和优先选择的JSON结构,就像这样?:
[
    {"id": 1, "description": "..."},
    {"id": 1, "description": "..."}
]

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