If in Chrome console I run proper JSON:
{"aaa":"bbb"}
I get:
SyntaxError: Unexpected token :
If however I run e.g.:
{aaa:"bbb"}
It dosen't complain. Also running below is fine:
aaa={"aaa":"bbb"}
I thought that proper JSON must have properties names wrapped in quotation marks so why is this happening? Is JS object notation not proper JSON?
We can have duplicate keys in a JSON object, and it would still be valid. The validity of duplicate keys in JSON is an exception and not a rule, so this becomes a problem when it comes to actual implementations.
JSON was derived from JavaScript. So, the JSON syntax resembles JavaScript object literal syntax. However, the JSON format can be accessed and be created by other programming languages too. Note: JavaScript Objects and JSON are not the same.
No, JavaScript objects cannot have duplicate keys. The keys must all be unique.
JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax.
The problem is caused by grammar/parsing context.
Given {"aaa":"bbb"}
as a program, this is a Block [statement] where "aaa" is a String followed by a colon and is thus Invalid Syntax. It can be minimally reproduced as: "aaa":"bbb"
, as the braces did nothing but add confusion.
Given {aaa:"bbb"}
as a program, this is a statement where aaa
(an Identifier) is a Label followed by the string "bbb"
(also in statement context). It is fine, but it does not return an object. Likewise, it is equivalent to aaa:"bbb"
in statement context.
Given aaa={"aaa":"bbb"}
as a program, now the {..}
is parsed in a expression context and treated as an Object Literal; the resulting object is assigned to the variable. An expression context can be forced with other grammar constructs, such as +{"aaa":"bbb"}
, ({"aaa":"bbb"})
or, more usefully, console.log({"aaa":"bbb"})
.
With all that out of the way, because the JavaScript Object Literal syntax simply didn't apply in two out of the three cases:
JSON is almost-but-not-quite a proper-subset of JavaScript Object Literals; use proper JSON tooling and validation.
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