Hacker News new | ask | show | jobs
by basil-rash 860 days ago
> The JSON syntax is nearly a strict subset of the popular programming language JavaScript.

What JSON isn’t valid JS?

2 comments

"Any JSON text is a valid JavaScript expression, but only after the JSON superset revision. Before the revision, U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR are allowed in string literals and property keys in JSON; but the same use in JavaScript string literals is a SyntaxError."

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...

"In fact, since JavaScript does not support bare objects, the simple statement {"k":"v"} will emit an error in JavaScript"

https://medium.com/@ExplosionPills/json-is-not-javascript-5d...

> "In fact, since JavaScript does not support bare objects, the simple statement {"k":"v"} will emit an error in JavaScript"

This is kind of a silly, "well technically". Its a valid expression. Its not a valid statement. It is valid javascript in the sense most people mean when asking the question if something is valid javascript.

Eh, this is slightly dated—{"k":"v"} does work in the WebKit and Blink consoles, and the superset proposal was approved, so those separators should work fine too.
The console evaluates what is passed to it as an expression, which is a different context from how scripts or modules are evaluated.
The one thing I've seen mentioned before is the use of "__proto__" as a object property key. Though it's valid syntax in both JSON and JS like any other string key, it somewhat uniquely does something different if interpreted as JS (setting the created object's prototype) than it does if interpreted as JSON.
That's fair, though somewhat benign barring a prototype pollution vulnerability. The object still behaves the same as it would had you JSON.parse'd the same string (Object.getPrototypeOf aside).
One simple issue would be if your object looks like

x = {"__proto__": {"foo": "bar"}}

now x.foo is "bar" if that's JS code, but undefined if you JSON.parse that same object definition from a string.