karnyj karnyj - 4 months ago 29
Javascript Question

Weird JSON parsing behavior in js, "Unexpected token :"

I recently came across an interesting issue with JSON objects in javascript, and i would appreciate if anyone could shed some light on this for me.

I looked around for duplicates but couldn't find any - i am sorry if i missed them.



as demonstrated in this jsfiddle, if you have a JS file and you create a JSON object without using it, it behaves differently depending on whether the keys(members) are wrapped in quotes or not.

valid code:

{ a: 1};


invalid code:
{ "a": 1 };


what you will get is an error message(in chrome, different for FF/IE, but still fails on syntax)


Uncaught SyntaxError: Unexpected token :


but if you use the object in some way, for example:
alert({ "a": 1 });


everything is ok again.



Can anyone explain why this happens?

Answer

The statement:

{ a: 1 };

is not an object literal. It's a block statement with one labeled expression in it. It's valid.

This:

{ "a": 1 };

is a syntax error because it's just not parseable. The quoted "a" starts an expression statement inside the block, but then the next token after the string is a colon, and there's no expression form that looks like an expression followed by a colon.

Now:

var x = { "a": 1 };

works because the "{" is not interpreted as the start of a block statement. That statement starts with var, so it's a variable declaration. Within the expression on the right side of the "=" token, the only thing that a "{" can mean is the start of an object literal. Similarly, note that:

({ "a": 1 });

is OK because the opening parenthesis makes the parser expect a nested subexpression, so again the "{" unambiguously means that it's the start of an object literal.