Skip to content
All tutorials

/tutorials/json-vs-javascript-objects

JSON Versus JavaScript Objects: Why JSON Is Stricter

JSON looks almost identical to a JavaScript object literal, but the two are not interchangeable. Here is exactly where they diverge.

5 min read

Run JSON Formatter

Where the confusion comes from

JSON's syntax was deliberately based on how JavaScript writes object and array literals, which is exactly why the two look so similar at a glance and why it is so easy to assume they are the same thing. They are not. JSON is a plain text data format with a fixed, small set of rules, while a JavaScript object literal is executable code that happens to share a similar look, and JavaScript's rules are considerably looser.

What JavaScript allows that JSON does not

  • Unquoted keys, such as writing name: "Frabs" instead of requiring the key itself to be in quotes.
  • Single quoted strings, alongside double quoted ones.
  • Trailing commas after the final item in an object or array.
  • Comments, both single line and block, written directly among the data.
  • Values that are not data at all, such as functions, undefined, or a reference to another variable in the surrounding code.

Why JSON deliberately gives up that flexibility

JSON is meant to move between completely different systems and programming languages, not just live inside JavaScript, and a strict, small rule set is exactly what makes that reliable. A parser written in Python, Java, or any other language only has to implement one simple, unambiguous grammar, without needing to understand JavaScript's full syntax, semantics, or ability to execute arbitrary code. This is also a safety benefit: parsing JSON never executes anything, whereas naively evaluating a JavaScript object literal as code can run arbitrary logic if the source is not trusted.

Converting between the two

In JavaScript itself, JSON.stringify turns an object into valid JSON text, automatically adding quotes around keys and dropping anything that cannot be represented, such as functions. JSON.parse does the reverse, turning JSON text back into a real JavaScript object. These two functions exist specifically because the two formats are not simply interchangeable, and a program needs an explicit, deliberate step to move between them.

Using the JSON Formatter to check which one you actually have

If a piece of text pasted from somewhere, a config file, an API response, a code snippet, fails to validate in the JSON Formatter, checking for single quotes, unquoted keys, trailing commas or comments is usually the fastest way to find out it was actually a JavaScript object literal rather than genuine JSON all along.