Amit Shah Amit Shah - 5 months ago 6
JSON Question

issue accessing JSON object using key name with . but works with []

What is the reason here while accessing JSON object using . gives error but using [] it works? what is the correct syntax to access the JSON object key?

This syntax gives the error:


var obj2G = obj.2G;


This syntax is working but why need to access this way?


var obj2G = obj["2G"];




var obj = {
"2G": [{
"essid": "SINGTEL-662F",
"authmode": "psk psk2",
"authkey": "0000026159",
"isEnable": "1",
"isHidden": "0",
"hwaddr": "E0:8E:3C:00:66:30",
"opmode": "ap"
}, {
"essid": "GUEST1-662F",
"authmode": "psk psk2",
"authkey": "aabbccddee",
"isEnable": "0",
"isHidden": "0",
"hwaddr": "",
"opmode": "ap"
}, {
"essid": "GUEST2-662F",
"authmode": "psk psk2",
"authkey": "aabbccddee",
"isEnable": "0",
"isHidden": "0",
"hwaddr": "",
"opmode": "ap"
}, {
"essid": "GUEST3-662F",
"authmode": "psk psk2",
"authkey": "aabbccddee",
"isEnable": "0",
"isHidden": "0",
"hwaddr": "62:8E:3C:00:66:33",
"opmode": "ap"
}],
"5G": [{
"essid": "SINGTEL-662F(5G)",
"authmode": "psk psk2",
"authkey": "0000026159",
"isEnable": "1",
"isHidden": "0",
"hwaddr": "E0:8E:3C:00:66:31",
"opmode": "ap"
}, {
"essid": "GUEST1(5G)-662F",
"authmode": "psk psk2",
"authkey": "aabbccddee",
"isEnable": "0",
"isHidden": "0",
"hwaddr": "6a:8e:3c:00:66:32",
"opmode": "ap"
}, {
"essid": "GUEST2(5G)-662F",
"authmode": "psk psk2",
"authkey": "aabbccddee",
"isEnable": "0",
"isHidden": "0",
"hwaddr": "",
"opmode": "ap"
}, {
"essid": "GUEST3(5G)-662F",
"authmode": "psk psk2",
"authkey": "aabbccddee",
"isEnable": "0",
"isHidden": "0",
"hwaddr": "6a:8e:3c:00:66:30",
"opmode": "ap"
}]
}

obj2G = obj["2G"];
console.log(obj2G);

obj2G = obj.2G;
console.log(obj2G);




Answer

If you use dot notation:

property must be a valid JavaScript identifier, i.e. a sequence of alphanumerical characters, also including the underscore ("_") and dollar sign ("$"), that cannot start with a number. For example, object.$1 is valid, while object.1 is not.

In that case, you have to use bracket notation:

property_name is a string. The string does not have to be a valid identifier; it can have any value, e.g. "1foo", "!bar!", or even " " (a space).

See the documentation: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors

It's worth mentioning that you have to use bracket notation if you want to access a property using a variable. For instance:

var myName = "foo";
var myObject = { foo: 42};
console.log(myObject.myName);//returns undefined

But:

var myName = "foo";
var myObject = { foo: 42};
console.log(myObject[myName]);//returns 42
Comments