Javascript JSON.parse 返回 [Object Object] 而不是值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47737093/
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.parse returning [Object Object] instead of value
提问by karthi
My API returning the JSON value like
我的 API 返回 JSON 值,如
[{"UserName":"xxx","Rolename":"yyy"}]
I need Usernameand RoleNamevalue seperatly i tried JSON.parse but its returning [Object Object] Please help me thanks in advance
我需要Username和RoleName价值分开我试过 JSON.parse 但它返回 [Object Object] 请帮助我提前谢谢
回答by Lajos Gallay
Consider the following:
考虑以下:
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
回答by Shalitha Suranga
You have an array. Then need to get 0thelement very first
你有一个array. 然后需要首先获取0th元素
This will work
这将工作
let unps = JSON.parse('[{"UserName":"xxx","Rolename":"yyy"}]')[0]
console.log(unps.UserName, unps.Rolename);
回答by codejockie
If your data is a string then you need to parse it with JSON.parse()otherwise you don't need to, you simply access it as is.
如果您的数据是一个字符串,那么您需要解析它,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 = data[0].UserName
const Rolename = data[0].Rolename
console.log(Username)
console.log(Rolename)

