JSON对象返回未定义的值 [英] JSON object returns undefined value
问题描述
我从http调用接收到JSON对象,并且试图从中提取值. JSON对象包含:
I am receiving a JSON object from a http call and I am trying to extract values from it. JSON object contains:
data:{"userid":"007", "role":"spy"}
我使用以下代码将角色属性分配给另一个变量,然后进行一些控制台日志检查:
I use the following code to assign role property 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);
日志产生:
type of data: object
data: [{"userid":"007", "role":"spy"}]
user role: undefined
我还尝试了另一种赋值方法:
Also I tried another method of assignment:
currentUserRole = data['role'];
但是currentUserRole仍然未定义.如何将JSON对象的属性设置为变量?
But currentUserRole remains undefined. How can I set a property of a JSON object to a variable?
推荐答案
根据日志的第二行(对JSON.stringify()
的调用),您的data
实际上是 array 的对象:
According to the second line of your log (the call to JSON.stringify()
), your data
is actually an array of objects:
[{"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)
尝试一下:
currentUserRole = data[0].role;
很显然,在生产就绪型代码中,您可能需要做一些额外的健全性检查,以确保data
实际上是一个至少包含一个元素的数组.
Obviously in production-ready code, you probably need to do some extra sanity checking to ensure that data
is in fact an array containing at least one element.
这篇关于JSON对象返回未定义的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!