我的API返回JSON值如下:
[{"UserName":"xxx","Rolename":"yyy"}]
我需要将Username
和RoleName
的值分别获取出来,我尝试使用JSON.parse但它返回了[Object Object],请帮帮我,谢谢。
我的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
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)
数组
。需要首先获取0th
元素。let unps = JSON.parse('[{"UserName":"xxx","Rolename":"yyy"}]')[0]
console.log(unps.UserName, unps.Rolename);
toString
输出[object Object]
(如果它是一个普通对象)。 - T.J. Crowder