通过ajax返回JSON值(对象)

时间:2013-08-22 13:28:02

标签: ajax json

假设我有一个像这样的json文件:

{
  "content": {
    "statistics": [
      {
        "key": "aaaa",
        "value": {
          "hits": 0,
          "misses": 0,
          "errors": 0,
          "hitRate": 0.0
        }
      },
      {
        "key": "bbbb",
        "value": {
          "hits": 0,
          "misses": 0,
          "errors": 0,
          "hitRate": 0.0
        }
      },
      {
        "key": "cccc",
        "value": {
          "hits": 0,
          "misses": 0,
          "errors": 0,
          "hitRate": 0.0
        }
      }
    ],
    "enabled": false
  },
  "meta": {
    "httpCode": 000
  }
}

并使用此ajax:

$.ajax({
    type: "GET",
    url: url,
    beforeSend: function(x) {
        if (x && x.overrideMimeType) {
            x.overrideMimeType("application/j-son;charset=UTF-8");
        }
    },
    dataType: "json",
    success: function(data) {
        console.log(data);
        var key=data["key"];
        console.log(key);
    }
});

但上面的代码不起作用,它不会从json返回键。如何显示键,值,命中等的所有值?非常感谢您的帮助

1 个答案:

答案 0 :(得分:1)

问题是层次结构中的key存在于您检查的不同级别。

鉴于data是您的JSON对象,key存在于data.content.statistics[index].key。因此,要打印出每个键,您需要以下内容:

for (var i = 0; i < data.content.statistics.length; i++) {
    var key = data.content.statistics[i].key;
    console.log(key);
}

然后您可以按如下方式访问每个值:

for (var i = 0; i < data.content.statistics.length; i++) {
    var key = data.content.statistics[i].key;
    var val = data.content.statistics[i].value;

    console.log("Hits: " + val.hits);
    console.log("Misses: " + val.misses);
    console.log("Errors: " + val.errors);
    console.log("Hit Rate: " + val.hitRate);
}