Guide · 6 min read
How to format JSON correctly
JSON is a deliberately small format, which is why it is everywhere and why its error messages are so unforgiving. A single trailing comma or a smart quote pasted from a document is enough to break an entire payload. Formatting JSON well is partly about readability and partly about catching those mistakes before they reach a server.
What valid JSON actually allows
The specification is short. A JSON document is a single value: an object, an array, a string, a number, true, false or null. Object keys must be double-quoted strings. Strings must use double quotes, never single quotes. Numbers cannot have leading zeros or a leading plus sign, and NaN and Infinity are not valid.
Everything JavaScript allows that JSON does not is a common source of breakage: comments, trailing commas, unquoted keys and single-quoted strings all look reasonable and all fail to parse.
Choosing an indentation width
Two spaces is the most widely used width for JSON because payloads nest deeply and four spaces pushes content off the screen quickly. Tabs are valid but display inconsistently in diff views and terminals.
Whatever you choose, apply it consistently across a repository. Mixed indentation makes version-control diffs noisy and hides the real change in a sea of whitespace.
Sorting keys, and when not to
Sorting object keys alphabetically makes two versions of a file easy to compare, which is useful for configuration files and translation bundles. It is a poor idea for fixtures or API examples where a logical grouping — identifier first, metadata last — helps a reader understand the shape.
Reading a parser error
Browser JSON errors report a position offset, such as 'Unexpected token } in JSON at position 148'. The reported position is where the parser gave up, which is usually just after the real mistake. Look at the character before it: a missing comma, an extra comma, or an unterminated string.
- Unexpected end of JSON input — a bracket or brace was never closed.
- Unexpected token o in JSON at position 1 — you passed an object where a string was expected.
- Bad control character in string literal — an unescaped newline or tab is inside a string.
Minify for transport, format for humans
Whitespace in JSON has no semantic meaning, so strip it before sending data over the wire and re-expand it when a person needs to read it. On a large payload, minifying commonly saves 15-30% of the bytes before compression even runs.