Is JavaScript object notation proper JSON?

If in the Chrome console I run the correct JSON:

{"aaa":"bbb"} 

I get:

 SyntaxError: Unexpected token : 

If, however, I run, for example:

 {aaa:"bbb"} 

Not complaining. Also works below:

 aaa={"aaa":"bbb"} 

I thought that the correct JSON should have property names enclosed in quotation marks, so why is this happening? Is the designation of a JS object not matching JSON?

+6
source share
1 answer

The problem is caused by the grammar / parsing context.

Given {"aaa":"bbb"} as a program, this is Block [statement] , where "aaa" is a string followed by a colon, and thus the syntax is invalid. It can be minimally reproduced as: "aaa":"bbb" , since the brackets did nothing but confusion.

Given {aaa:"bbb"} as a program, this is a statement in which aaa (identifier) ​​is Label followed by the string "bbb" (also in the context of the statement). This is normal, but it does not return an object. Similarly, this is equivalent to aaa:"bbb" in the context of the statement.

Given aaa={"aaa":"bbb"} as a program, now {..} parsed in the context of the expression and treated as 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 useful, console.log({"aaa":"bbb"}) .

With all of this in mind, the JavaScript Object Literal syntax just didn't apply in two of three cases:

JSON is an almost-but-not-completely subset of JavaScript object literals; Use proper JSON rigging and validation.

+13
source

Source: https://habr.com/ru/post/975808/


All Articles