javascript JSON 对象返回未定义的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23507807/
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
JSON object returns undefined value
提问by pbd
I am receiving a JSON object from a http call and I am trying to extract values from it. JSON object contains:
我从 http 调用中接收到一个 JSON 对象,我正在尝试从中提取值。JSON 对象包含:
data:{"userid":"007", "role":"spy"}
I use the following code to assign roleproperty to another variable followed by some console log checks:
我使用以下代码将角色属性分配给另一个变量,然后进行一些控制台日志检查:
currentUserRole = data.role;
console.log("type of data: "+typeof(data));
console.log("data: "+JSON.stringify(data));
console.log("user role: "+currentUserRole);
The logs produce:
日志产生:
type of data: object
data: [{"userid":"007", "role":"spy"}]
user role: undefined
Also I tried another method of assignment:
我也尝试了另一种分配方法:
currentUserRole = data['role'];
But currentUserRole remains undefined. How can I set a property of a JSON object to a variable?
但是 currentUserRole 仍然是undefined。如何将 JSON 对象的属性设置为变量?
回答by Adam Batkin
According to the second line of your log (the call to JSON.stringify()), your datais actually an arrayof objects:
根据您日志的第二行(对 的调用JSON.stringify()),您data实际上是一个对象数组:
[{"userid":"007", "role":"spy"}]
If it was an object as you are expecting, it would look like this:
如果它是您期望的对象,它看起来像这样:
{"userid":"007", "role":"spy"}
(the difference is subtle, but notice the missing square brackets)
(差异很小,但请注意缺少方括号)
Try this:
试试这个:
currentUserRole = data[0].role;
Obviously in production-ready code, you probably need to do some extra sanity checking to ensure that datais in fact an array containing at least one element.
显然,在生产就绪代码中,您可能需要进行一些额外的完整性检查以确保它data实际上是一个包含至少一个元素的数组。
回答by Jamsheed Kamarudeen
It is a list. Try data[0].role
它是一个列表。尝试data[0].role

