hank-builds.com

How to Format JSON - Pretty Print & Validate Guide

What is JSON Formatting?

JSON formatting (or "pretty-printing") adds consistent indentation and line breaks to make JSON data readable. Minified JSON saves space for transmission but is hard to read. Formatted JSON is essential for debugging, code review, and documentation.

Indentation Styles

There are three common indentation styles for JSON:

2 spacesCompact, widely used in JavaScript/Node.js projects and npm packages. This is what JSON.stringify(data, null, 2) produces.
4 spacesMore readable for deeply nested structures. Common in Python and Java ecosystems.
TabCustomizable width in each editor. Some teams prefer tabs for accessibility reasons.

There's no "correct" choice — use whatever your team standardizes on.

Common JSON Errors

These are the most frequent mistakes when writing JSON by hand:

  • Trailing commas — JSON does not allow a comma after the last item in an array or object: {"a": 1, "b": 2,} is invalid.
  • Single quotes — JSON requires double quotes for strings: {'name': 'John'} is invalid.
  • Unquoted keys — All keys must be quoted: {name: "John"} is invalid.
  • Comments — Standard JSON does not support comments. Use JSONC or JSON5 for that.
  • Missing quotes on strings — Values like hello must be "hello".

Sorting Keys

Sorting object keys alphabetically makes JSON easier to compare and review. When two JSON objects have the same data but different key ordering, sorting both by keys makes them identical. This is especially useful before committing configuration files to version control.

Minification

JSON minification removes all unnecessary whitespace (spaces, tabs, newlines) to reduce file size. This is important for API responses and network transmission where every byte counts. A typical JSON payload can be 30-60% smaller when minified.