Hacker News new | comments | show | ask | jobs | submit login

What about a JSON object do you think is invalid Javascript?

It's a valid subset of Javascript (or at least was initially meant to be), but a JSON object (as opposed to an array) isn't a valid stand-alone Javascript expression, and an attempt to eval it will return an error:

    > eval('{"key": "value"}');
    SyntaxError: missing ; before statement
You can get around this by using parens:

    > eval('({"key": "value"})');
    Object { key: "value" }
But accidentally including a JSON URL in a script tag should fail to evaluate if there's an object at the top level.

All JSON literals are valid JS expressions but not all are valid statements. The two are different parts of the JS grammar.

As script blocks expect one or more statements to execute, the hack relies on the fact that some JSON (array literals) also happen to be valid statements in addition to expressions.

While the person you're responding to might genuinely be confused about JSON usually being valid JavaScript, arbitrary JSON isn't guaranteed to be: http://timelessrepo.com/json-isnt-a-javascript-subset

Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact