18

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?!

steady_progress
  • 3,311
  • 10
  • 31
  • 62

4 Answers4

28

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

Yuval Perelman
  • 4,499
  • 1
  • 22
  • 32
6

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);
Mahmoud Kassem
  • 409
  • 5
  • 9
0

You will need to assign that to a var and then access it.

var object = {id: "someId"};
console.log(object);
alert(object["id"]);
Pritam Banerjee
  • 17,953
  • 10
  • 93
  • 108
0

In JavaScript, object properties can be accessed with . operator or with associative array indexing using []. I.e. object.property is equivalent to object["property"]

You can try:

var obj = JSON.parse(Object);
alert(obj.id);