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?

5
  • possible duplicate of Access / process (nested) objects, arrays or JSON Commented May 7, 2014 at 2:44
  • 1
    JSON.stringify(data) clearly shows that data is an array with one element, an object. Commented May 7, 2014 at 2:44
  • 1
    FYI: JSON is a string. You can't set properties on it. This doesn't have anything to do with JSON. Commented May 7, 2014 at 2:45
  • 1
    ^ There's no such thing as a "JSON Object" Commented May 7, 2014 at 2:46
  • 1
    @FelixKling: +1 on the JSON object article Commented May 7, 2014 at 2:50

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

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 ;)
ofcourse. but now that someone else gave a good answer, I would leave it at that. Will do it in my later replies

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.