JSON.parse returning [Object Object] instead of va

2020-07-13 11:37发布

问题:

My API returning the JSON value like

[{"UserName":"xxx","Rolename":"yyy"}]

I need Username and RoleName value seperatly i tried JSON.parse but its returning [Object Object] Please help me thanks in advance

回答1:

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



回答2:

You have an array. Then need to get 0th element very first

This will work

let unps =  JSON.parse('[{"UserName":"xxx","Rolename":"yyy"}]')[0]
console.log(unps.UserName, unps.Rolename);



回答3:

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.

// 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)