javascript 从 json 响应中获取值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5554270/
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
Get value from json response
提问by Simpanoz
I have following JSON response received from server:
我从服务器收到以下 JSON 响应:
{
"msg": "S",
"comments": {
"iRecords": [{
"id": "9",
"bid": "1",
"uid": "5",
"comment": "This is # 009",
"adate": "Tuesday, 5th April, 2011 11:15:05",
"status": "1",
"userid": "5",
"username": "pavlos",
"oauthprovider": "l",
"profile_link": null
}]
}
}
Iam using following javascript/jQuery to get values but it is showing nothing:
我正在使用以下 javascript/jQuery 来获取值,但它什么也没显示:
obj = jQuery.parseJSON(responseText);
alert(obj.comments.iRecords[adate]);
Note: alert(obj.msg);
is working fine.
注意:alert(obj.msg);
工作正常。
How can I get value of adate in Javascript.
如何在 Javascript 中获取 adate 的值。
Thanks in advance
提前致谢
回答by McStretch
iRecords
holds an array of objects, so you need to access the first index of the array to get to the first object:
iRecords
持有一个对象数组,因此您需要访问数组的第一个索引以获取第一个对象:
obj = jQuery.parseJSON(responseText);
alert(obj.comments.iRecords[0]["adate"]);
or
或者
alert(obj.comments.iRecords[0].adate);
回答by Quentin
You haven't defined a variable called adate
and iRecords
is an array
你还没有定义一个名为的变量adate
,它iRecords
是一个数组
If you use square bracket notation then you have to pass in a string containing the property name, not a variable with the same name as the property.
如果使用方括号表示法,则必须传入包含属性名称的字符串,而不是与属性同名的变量。
obj.comments.iRecords[0].adate;
回答by Alex K.
obj has a comments object which has an iRecods member which is an array with 1 element so;
obj 有一个 comments 对象,它有一个 iRecods 成员,它是一个包含 1 个元素的数组;
x = obj.comments.iRecords[0].adate