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
Accessing JSON data
提问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 col1
and col2
, so something like:
它是一个包含 2 个元素的数组,其中包含col1
和col2
,因此类似于:
alert(data.d[1].col1);
(0
is 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:
在人类中:
- start at data variable
- go to d property.
- d is an array, so look up the value at index 1 (second value)
- look up the col1 property of that value.
- 从数据变量开始
- 去d属性。
- d 是一个数组,因此在索引 1(第二个值)处查找值
- 查找该值的 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的工作示例。