Accessing JSON object keys having spaces
JavascriptJsonJavascript Problem Overview
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?
Javascript Solutions
Solution 1 - Javascript
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:
Solution 2 - Javascript
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!