我的API返回JSON值,如
[{"UserName":"xxx","Rolename":"yyy"}]
我需要Username
和RoleName
值,我试过JSON.parse,但是它返回[Object Object]请提前帮助我
答案 0 :(得分:7)
请考虑以下事项:
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

答案 1 :(得分:0)
你有array
。然后需要首先获得0th
元素
这将有效
let unps = JSON.parse('[{"UserName":"xxx","Rolename":"yyy"}]')[0]
console.log(unps.UserName, unps.Rolename);

答案 2 :(得分:0)
如果您的数据是字符串,那么您需要使用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)