Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is JavaScript Object notation proper JSON? [duplicate]

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?

like image 497
spirytus Avatar asked Sep 25 '14 02:09

spirytus


People also ask

Does JSON object allow duplicate keys?

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.

Are JavaScript objects and JSON equivalent?

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.

Does JavaScript object allow for duplicate keys?

No, JavaScript objects cannot have duplicate keys. The keys must all be unique.

What type of data is JavaScript Object Notation?

JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax.


1 Answers

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.

like image 109
user2864740 Avatar answered Oct 16 '22 17:10

user2864740