javascript says JSON object property is undefined although it's not

44,192

Solution 1

Looks like your json object is not really an object, it's a json string. in order to use it as an object you will need to use a deserialization function like JSON.parse(obj). Many frameworks have their own implementation for deserializing a JSON string.
When you try to do alert(obj) with a real object the result would be [object Object] or something like that

Solution 2

Your JSON is not parsed, so in order for JavaScript to be able to access it's values you should parse it first as in line 1:

var result = JSON.parse(object);

After parsing your JSON Object, you can access it's values as following:

alert(result.id);
Share:
44,192
steady_progress
Author by

steady_progress

Updated on November 25, 2021

Comments

  • steady_progress
    steady_progress over 2 years

    I have a json-object, which I print to the screen (using alert()-function):

    alert(object);
    

    Here is the result:

    enter image description here

    Then I want to print the value of the id to the screen:

        alert(object["id"]); 
    

    The result is this:

    enter image description here

    As you can see, the value of key "id" is not(!!!) undefined.

    What the hell is going on here?!

  • Artem
    Artem almost 7 years
    I was about posting the same! :)
  • steady_progress
    steady_progress almost 7 years
    Thank you for your help! That was the solution.
  • sayalok
    sayalok over 5 years
    my problem is different but your idea help me to solve this