jQuery 访问 JSON 数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6706374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:15:55  来源:igfitidea点击:

Accessing JSON data

jsonjquery

提问by oshirowanen

If I am given the following data by a web-service:

如果我通过网络服务获得以下数据:

{
    "d": [
        {
            "col1": "col 1 data 1",
            "col2": "col 2 data 1"
        },
        {
            "col1": "col 1 data 2",
            "col2": "col 1 data 2"
        }
    ]
}

how do I access the second col1?

如何访问第二个 col1?

As the following:

如下:

success: function( data ) {
         alert( data.d ) ;
},

gives me:

给我:

[object Object],[object Object]

回答by Nanne

Its an array with 2 elements containing col1and col2, so something like:

它是一个包含 2 个元素的数组,其中包含col1col2,因此类似于:

alert(data.d[1].col1);

(0is the first element, and then you choose "col1")

0是第一个元素,然后你选择“col1”)

回答by Rafay

success:function(data){
data = JSON.parse(data); // you will have to parse the data first
alert(data.d[0].col1);

回答by cwallenpoole

alert( data.d[1].col1 ) ;

In human:

在人类中:

  1. start at data variable
  2. go to d property.
  3. d is an array, so look up the value at index 1 (second value)
  4. look up the col1 property of that value.
  1. 从数据变量开始
  2. 去d属性。
  3. d 是一个数组,因此在索引 1(第二个值)处查找值
  4. 查找该值的 col1 属性。

May I suggest console.log? In Chrome and with Firefox/Firebug it will give you a nice log message which tells you more about your data.

我可以建议console.log吗?在 Chrome 和 Firefox/Firebug 中,它会给你一个很好的日志消息,告诉你更多关于你的数据。

回答by Ben Everard

Try this:

尝试这个:

var json = {
    "d": [
        {
            "col1": "col 1 data 1",
            "col2": "col 2 data 1"
        },
        {
            "col1": "col 1 data 2",
            "col2": "col 1 data 2"
        }
    ]
};

alert(json.d[1].col1);

Specify the array index of d(starts with 0, so this would be 1) and then you can access child items. Here's a working example on jsFiddle.

指定数组索引d(从 0 开始,所以这将是 1),然后您就可以访问子项。这是一个关于 jsFiddle工作示例