JSON object returns undefined value

前端 未结 2 1140
Happy的楠姐
Happy的楠姐 2021-01-18 20:45

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\"}
         


        
相关标签:
2条回答
  • 2021-01-18 21:02

    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.

    0 讨论(0)
  • 2021-01-18 21:03

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

    0 讨论(0)
提交回复
热议问题