baltusaj baltusaj - 3 months ago 30
Javascript Question

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
alert(obj["No. of interfaces"]); //Return 'undefined'


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

Answer

The way to do this is via the bracket notation.

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

For more info read out here: