Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing JSON object keys having spaces [duplicate]

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?

like image 288
Usman Avatar asked Apr 25 '12 07:04

Usman


People also ask

Are spaces allowed in JSON keys?

Whitespace (Space, Horizontal tab, Line feed or New line or Carriage return) does not matter in JSON. It can also be minified with no affect to the data. Object literal names MUST be lowercase (ie – null, false, true etc).

Are duplicate keys valid in JSON?

We can have duplicate keys in a JSON object, and it would still be valid.

How do you access object keys with spaces?

Use bracket notation to access a key that contains a space in an object, e.g. obj['my key'] . The bracket [] notation syntax allows us to access an object's key, even if it contains spaces, hyphens or special characters.

Can object keys have spaces?

Object Keys Are Strings Object keys with underscores and camelCase (no spaces) don't require the bracket syntax, but object keys with spaces and hyphens do. You may prefer the code readability of the . dot syntax, in which case you'll want to avoid spaces in your object keys: you might write object.


2 Answers

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:

  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
like image 83
Joseph Avatar answered Oct 18 '22 18:10

Joseph


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!
like image 34
Laser42 Avatar answered Oct 18 '22 18:10

Laser42