Skip to content Skip to sidebar Skip to footer

Json.parse Returning [object Object] Instead Of Value

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

Solution 1:

Consider the following:

var str = '[{"UserName":"xxx","Rolename":"yyy"}]'; // your response in a stringvar parsed = JSON.parse(str); // an *array* that contains the uservar user = parsed[0];         // a simple userconsole.log(user.UserName);   // you'll get xxxconsole.log(user.Rolename);   // you'll get yyy

Solution 2:

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 formatconst data = [{"UserName":"xxx","Rolename":"yyy"}];

const username = data[0].UserNameconst rolename = data[0].Rolenameconsole.log(username)
console.log(rolename)

// if data is in string formatconst strData = JSON.parse('[{"UserName":"xxx","Rolename":"yyy"}]');

constUsername = strData[0].UserNameconstRolename = strData[0].Rolenameconsole.log(Username)
console.log(Rolename)

Solution 3:

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

Post a Comment for "Json.parse Returning [object Object] Instead Of Value"