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?
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).
We can have duplicate keys in a JSON object, and it would still be valid.
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.
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.
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:
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With