如何在json数据概念中访问结果?

时间:2016-09-21 07:11:36

标签: jquery json ajax

任何人都可以解释我如何访问json数据的结果。 这是我的json值,这是我通过

进入ajax成功
success: function (data) {
    console.log(data.d)
    console.log("Success")
},

对于上面的代码,我得到的是:

{
  "locations": {
    "location": [{
      "invid": "1634",
      "usrinvid": "1",
      "locname": "My Location",
      "businessunit": "My Business Unit",
      "organization": "My Organization",
      "desc": "This is the location created by the system for the new Business Owner. It can be renamed.",
      "netqtyavail": "0.000"
    }, {
      "invid": "1647",
      "usrinvid": "2",
      "locname": "My Second Location",
      "businessunit": "My Business Unit",
      "organization": "My Organization",
      "desc": null,
      "netqtyavail": "0.000"
    }, {
      "invid": "1698",
      "usrinvid": "20",
      "locname": "test dsf - Loc 1",
      "businessunit": "test dsf",
      "organization": "My Organization",
      "desc": "This location was added compulsorily for the new business unit -'test dsf'. You can update the name, description and other details of this location. You may also delete this location if you have added other location for 'test dsf'",
      "netqtyavail": "0.000"
    }]
  }
}

在解析成功后的结果如下:

success: function (data) {
    console.log(JSON.parse(data.d))
    console.log("Success")
},

结果是:

enter image description here

1 个答案:

答案 0 :(得分:1)

在您的情况下,JSON.parse(data.d)的返回值是一个对象:

var obj = JSON.parse(data.d);

您可以像使用任何其他对象的属性一样使用该对象的属性。

你问题中的对象有点奇怪:它只有一个名为locations的属性,它是一个只有一个属性location的对象,它是一个阵列的位置。我说这很奇怪,因为1.它似乎是一种不必要的嵌套级别,而且location是一个奇怪的名称,用于数组的位置(复数)。

但是,如果我们想要访问这些位置,我们可以通常的方式这样做:

console.log(obj.locations.location.length); // 3

或者您可以通过循环遍历数组来列出这些位置的名称:

obj.locations.location.forEach(function(entry) {
    console.log(entry.locname);
});