Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON object returns undefined value

I am receiving a JSON object from a http call and I am trying to extract values from it. JSON object contains:

data:{"userid":"007", "role":"spy"}

I use the following code to assign role property to another variable followed by some console log checks:

    currentUserRole = data.role;    
    console.log("type of data: "+typeof(data));
    console.log("data: "+JSON.stringify(data));
    console.log("user role: "+currentUserRole);

The logs produce:

type of data: object
data: [{"userid":"007", "role":"spy"}]
user role: undefined

Also I tried another method of assignment:

currentUserRole = data['role'];

But currentUserRole remains undefined. How can I set a property of a JSON object to a variable?

like image 495
pbd Avatar asked May 07 '14 02:05

pbd


1 Answers

According to the second line of your log (the call to JSON.stringify()), your data is actually an array of objects:

[{"userid":"007", "role":"spy"}]

If it was an object as you are expecting, it would look like this:

{"userid":"007", "role":"spy"}

(the difference is subtle, but notice the missing square brackets)

Try this:

currentUserRole = data[0].role;

Obviously in production-ready code, you probably need to do some extra sanity checking to ensure that data is in fact an array containing at least one element.

like image 146
Adam Batkin Avatar answered Oct 12 '22 22:10

Adam Batkin