[javascript] Accessing JSON object keys having spaces

I have following json object:

{ "id": "109",
  "No. of interfaces": "4" }

Following lines work fine:

alert(obj.id);
alert(obj["id"]);

But if keys have spaces then I cannot access their values e.g.

alert(obj."No. of interfaces"); //Syntax error

How can I access values, whose key names have spaces? Is it even possible?

This question is related to javascript json

The answer is


The way to do this is via the bracket notation.

_x000D_
_x000D_
var test = {_x000D_
    "id": "109",_x000D_
    "No. of interfaces": "4"_x000D_
}_x000D_
alert(test["No. of interfaces"]);
_x000D_
_x000D_
_x000D_

For more info read out here:


The answer of Pardeep Jain can be useful for static data, but what if we have an array in JSON?

For example, we have i values and get the value of id field

alert(obj[i].id); //works!

But what if we need key with spaces?

In this case, the following construction can help (without point between [] blocks):

alert(obj[i]["No. of interfaces"]); //works too!