Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
158
rated 0 times [  162] [ 4]  / answers: 1 / hits: 26043  / 10 Years ago, wed, may 7, 2014, 12:00:00

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?


More From » json

 Answers
157

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.


[#71147] Monday, May 5, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
byrondonavanc

Total Points: 675
Total Questions: 107
Total Answers: 105

Location: Peru
Member since Fri, Oct 14, 2022
2 Years ago
byrondonavanc questions
;