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
The JSON. parse() method parses a string and returns a JavaScript object.
The JSON. parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.
Stringify a JavaScript ObjectUse the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);
It`s ok to use it with some primitives like Numbers, Strings or Booleans. As you can see, you can just lose unsupported some data when copying your object in such a way. Moreover, JavaScript won`t even warn you about that, because calling JSON. stringify() with such data types does not throw any error.
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
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 = strData[0].UserName
const Rolename = strData[0].Rolename
console.log(Username)
console.log(Rolename)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With