A practical guide to formatting, validating and converting JSON

7 min read
json
guide

JSON is the default wire format for almost everything, and most of the pain people have with it comes down to three things: whitespace, invalid syntax, and the wrong target format.

Formatting

Two spaces is the de facto standard for JavaScript ecosystems; four is common in Java and Python codebases. Tabs are the accessible choice because a reader can set their own width. Pick one per repository and let a formatter enforce it.

Sorting keys is underrated. Two payloads that differ only in key order produce a noisy diff; sort both and the real change stands out.

Validating

The most common parse errors are boring and fixable:

  • A trailing comma after the last item in an object or array.
  • Single quotes instead of double quotes.
  • Unescaped newlines or quotes inside a string.
  • `NaN`, `Infinity` or `undefined`, none of which are valid JSON.
  • A BOM or stray character before the opening brace.

A validator that reports line and column turns a five-minute hunt into a five-second fix.

Converting

Convert to YAML when a human has to edit the file — configuration, CI pipelines, Kubernetes manifests. Convert to CSV when the data is a flat array of records and the destination is a spreadsheet. Convert to XML when a legacy system demands it, and be careful with attributes versus child elements.

Rule of thumb

Format for reading, minify for shipping, validate before both.

Tools from this article

← All articles