Valid, readable JSON

JSON is the format most web APIs exchange data in: objects in braces with keys in double quotes, arrays in brackets, strings, numbers, true, false and null. APIs often return it minified on a single line: formatting it with indentation makes it readable, minifying it strips the spaces and saves bytes.

The syntax is stricter than JavaScript's: no trailing comma after the last element, no comments, no single quotes, keys always in double quotes. These are the most common mistakes when writing JSON by hand, and the parser reports them with the exact position.

Sorting the keys alphabetically does not change the meaning, since key order does not matter in a JSON object, but it makes two responses or two configuration files much easier to compare with a diff.

Common mistakes

  • Leaving a comma after the last element of an object or array: JSON does not accept it.
  • Using single quotes or unquoted keys, as in JavaScript: JSON needs double quotes.
  • Writing NaN, Infinity or undefined: they are not JSON values; use null.

Frequently asked questions

Is the JSON I paste sent to a server?

No: formatting and validation happen in the browser with JSON.parse. Only short JSON goes into the page address, so the page can be shared.

Why do very large numbers change?

JSON.parse uses JavaScript floating-point numbers, exact up to 2⁵³: an ID such as 12345678901234567890 gets rounded. APIs with large IDs usually send them as strings.

How does JSON differ from JSON5?

JSON5 is an extension that allows comments, trailing commas and single quotes; handy for configuration files, but it is not standard JSON and JSON.parse rejects it.

How this calculation works

The text is read with JSON.parse, which applies the RFC 8259 grammar; on an error the position the browser reports is turned into a line and column. The result is written back with JSON.stringify, with 2 or 4 spaces or a tab per level, or with no spaces. With sorting, the keys of every object are sorted recursively by Unicode code point. Sizes are in UTF-8 bytes.