[英]JSON.parse returning [Object Object] instead of value
我的 API 返回 JSON 值,如
[{"UserName":"xxx","Rolename":"yyy"}]
我需要Username
和RoleName
值分别我试过 JSON.parse 但它返回 [Object Object] 请帮助我提前谢谢
请考虑以下事项:
var str = '[{"UserName":"xxx","Rolename":"yyy"}]'; // your response in a string var parsed = JSON.parse(str); // an *array* that contains the user var user = parsed[0]; // a simple user console.log(user.UserName); // you'll get xxx console.log(user.Rolename); // you'll get yyy
你有一个array
。 然后需要首先获取0th
元素
这将工作
let unps = JSON.parse('[{"UserName":"xxx","Rolename":"yyy"}]')[0] console.log(unps.UserName, unps.Rolename);
如果您的数据是一个字符串,那么您需要使用JSON.parse()
解析它,否则您不需要,您只需按原样访问它。
// if data is not in string format const data = [{"UserName":"xxx","Rolename":"yyy"}]; const username = data[0].UserName const rolename = data[0].Rolename console.log(username) console.log(rolename) // if data is in string format const strData = JSON.parse('[{"UserName":"xxx","Rolename":"yyy"}]'); const Username = strData[0].UserName const Rolename = strData[0].Rolename console.log(Username) console.log(Rolename)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.