从 javascript 访问 JSON 元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10842841/
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 elements from javascript
提问by Luis D Urraca
$.getJSON('http://23.21.128.153:3000/api/v1/holidays', function(data){
alert("this: " + data.holiday[0].name);
});
I'm trying to access the "name" attribute of the first element of my JSON response but without success, can anyone tell me what I'm doing wrong.
我正在尝试访问 JSON 响应的第一个元素的“名称”属性,但没有成功,谁能告诉我我做错了什么。
回答by cambraca
Try this:
尝试这个:
data[0].holiday.name
The data
looks like this:
该data
如下所示:
[
{
"holiday":{
"id":1,
"date":"2012-05-01",
"name":"Dia del trabajo",
"description":"",
"country_id":1,
"moved_date":"2012-04-30"
}
},
{
"holiday":{...}
},
...]
So, you need to select the first element from the main array (data[0]
), then get its holiday
property (data[0].holiday
), and then get its name
property.
因此,您需要从主数组中选择第一个元素 ( data[0]
),然后获取其holiday
属性 ( data[0].holiday
),然后获取其name
属性。