【发布时间】:2014-05-07 02:41:55
【问题描述】:
我从 http 调用中接收到一个 JSON 对象,并试图从中提取值。 JSON 对象包含:
data:{"userid":"007", "role":"spy"}
我使用以下代码将 role 属性分配给另一个变量,然后进行一些控制台日志检查:
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
我还尝试了另一种分配方法:
currentUserRole = data['role'];
但 currentUserRole 仍然未定义。如何将 JSON 对象的属性设置为变量?
【问题讨论】:
-
JSON.stringify(data)清楚地表明data是一个数组,其中包含一个元素,即一个对象。 -
仅供参考:JSON 是一个字符串。您不能在其上设置属性。这与 JSON 没有任何关系。
-
@FelixKling:关于 JSON 对象文章的 +1
标签: javascript json