如何在方括号内解析Json响应?

时间:2016-04-08 08:39:15

标签: javascript

我收到以下Json回复:

"kind": "analytics#gaData",
"id": "c",
"rows": [
    [
      "/de/cart.aspx",
      "0"
    ],
    [
      "/de/cart_details.aspx",
      "0"
    ],
    [
      "/de/cart_login.aspx",
      "0"
    ],
    [
      "/de/order_summary.aspx",
      "0"
    ],
    [
      "/fr/cart.aspx",
      "0"
    ],
    [
      "/fr/cart_details.aspx",
      "0"
    ],
    [
      "/fr/cart_login.aspx",
      "0"
    ],
    [
      "/fr/order_summary.aspx",
      "0"
    ],
    [
      "/it/cart.aspx",
      "0"
    ],
    [
      "/it/cart_details.aspx",
      "0"
    ],
    [
      "/it/cart_login.aspx",
      "0"
    ],
    [
      "/it/order_summary.aspx",
      "0"
    ]
  ]

Javascript中,如何才能循环遍历此数组(?)以检索其数据?

1 个答案:

答案 0 :(得分:2)

就像你跟踪任何其他阵列一样。简单地说,构成此数组的对象不是将其属性存储在地图中的属性名称下,而是将其属性存储在数组中的给定索引下。

theJsonObject.rows.forEach( function(row) {
    var url = row[0];
    var n = row[1];
    do stuff with url and n...
});

forEach可以替换为适合特定情况的任何内容。例如,如果您想将其转换为具有命名属性的常规对象数组:

var withNamedProperties = theJsonObject.rows.map( function(row) {
    return {
        url:row[0],
        n:row[1]
    };
});