Accessing JSON object keys having spaces

JavascriptJson

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionUsmanView Question on Stackoverflow
Solution 1 - JavascriptJosephView Answer on Stackoverflow
Solution 2 - JavascriptLaser42View Answer on Stackoverflow