Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 help me thanks in advance

like image 881
karthi Avatar asked Dec 10 '17 08:12

karthi


People also ask

Does JSON parse return an object?

The JSON. parse() method parses a string and returns a JavaScript object.

What happens if you JSON parse an 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.

How do I Stringify a JSON object?

Stringify a JavaScript ObjectUse the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);

Is it bad to use JSON Stringify?

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.


2 Answers

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
like image 116
Lajos Gallay Avatar answered Sep 22 '22 16:09

Lajos Gallay


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)
like image 28
codejockie Avatar answered Sep 25 '22 16:09

codejockie