5

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?

pbd
  • 423
  • 3
  • 8
  • 19
  • possible duplicate of [Access / process (nested) objects, arrays or JSON](http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – Felix Kling May 07 '14 at 02:44
  • 1
    `JSON.stringify(data)` clearly shows that `data` is an **array** with one element, an **object**. – Felix Kling May 07 '14 at 02:44
  • 1
    FYI: JSON *is a string*. You can't set properties on it. This doesn't have anything to do with JSON. – Hamish May 07 '14 at 02:45
  • 1
    ^ [There's no such thing as a "JSON Object"](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/) – Felix Kling May 07 '14 at 02:46
  • 1
    @FelixKling: +1 on the JSON object article – pbd May 07 '14 at 02:50

2 Answers2

15

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.

Adam Batkin
  • 51,711
  • 9
  • 123
  • 115
0

It is a list. Try data[0].role

Jamsheed Kamarudeen
  • 718
  • 2
  • 7
  • 14
  • 3
    Hiya, I know this seems obvious to you, but don't forget that total n00bs will probably stumble across your solution at some future time. Can you give a brief explanation for why this solution works (in this case something about it being an object embedded in an array and needing to index into it first)? For The Children ;) – Taryn East May 07 '14 at 03:05
  • ofcourse. but now that someone else gave a good answer, I would leave it at that. Will do it in my later replies – Jamsheed Kamarudeen May 08 '14 at 04:28