119

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?

Usman
  • 8,227
  • 14
  • 69
  • 103

2 Answers2

229

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:

Pardeep Jain
  • 78,495
  • 36
  • 155
  • 210
Joseph
  • 113,089
  • 28
  • 177
  • 225
  • 1
    Thank you for referencing the documentation. It is surprising how many answers lack this important detail. – samurai_jane Oct 30 '17 at 10:06
  • 6
    What's difference between the question and answer? – Vishal Kumar Sahu Nov 11 '18 at 23:36
  • 1
    The answer uses bracket notation `test['No. of interfaces']` instead of dot notation `test."No. of interfaces"`. – benjaki Sep 29 '20 at 12:55
  • How do you accomplish the same thing when doing object deconstructing? `const { Pricing, Location, data[0]["Product 1"] } = data[0]` << doesn't work `const { Pricing, Location, ["Product 1"] } = data[0]` << doesn't work – Vinn Apr 19 '22 at 04:20
9

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!
Laser42
  • 582
  • 2
  • 6
  • 18