Dev / IT6 min read

JSON Formatting and Validation: A Developer's Complete Guide

Learn how to format, validate, and minify JSON correctly. Covers JSON syntax rules, common errors, indentation best practices, and when to minify vs pretty-print for APIs and config files.

JSON (JavaScript Object Notation) is the lingua franca of modern APIs and configuration files. But raw JSON from an API response or a log file is often a single unreadable line. Knowing how to format, validate, and minify JSON correctly is a daily skill for developers.

What is JSON Formatting?

JSON formatting — also called pretty-printing or beautifying — adds consistent indentation and line breaks so nested objects and arrays are visually readable. A formatter takes this:

{"name":"Alice","age":30,"roles":["admin","user"]}

And turns it into this:

{
  "name": "Alice",
  "age": 30,
  "roles": [
    "admin",
    "user"
  ]
}

The two-space indent is the most common convention, but four spaces is also widely used — especially in Python communities and some linters. The data itself is identical; only the whitespace changes.

JSON Syntax Rules

JSON has strict syntax rules. Break any of them and the entire document is invalid. The most common mistakes:

  • Trailing commas are not allowed. {"a":1,"b":2,} is invalid JSON even though JavaScript allows it. JSONC (JSON with Comments) is a separate format supported by VS Code and TypeScript configs.
  • Keys must be double-quoted strings. {name:"Alice"} is JavaScript object syntax, not JSON.
  • Comments are not allowed. // this is invalid will cause a parse error in standard JSON parsers.
  • String values must use double quotes. Single quotes like {'name':'Alice'} are invalid.
  • Numbers cannot have leading zeros. 007 is invalid; use 7.

How to Validate JSON

Validation checks whether your JSON is syntactically correct. In JavaScript, the simplest approach is wrapping JSON.parse() in a try/catch:

try {
  const data = JSON.parse(input)
  console.log('Valid JSON', data)
} catch (err) {
  console.error('Invalid JSON:', err.message)
}

Good JSON validators go further — they report the exact line and column where the error occurred, making it much faster to locate a missing bracket or a trailing comma buried in a 500-line config file.

When to Minify JSON

Minification removes all whitespace, reducing file size. For a large JSON payload with thousands of keys, this can cut size by 20–40%. Use minified JSON for:

  • API responses — less data transferred means faster load times, especially on mobile networks.
  • Storing JSON in databases — text columns hold more records when whitespace is removed.
  • JavaScript bundles — JSON imported into a bundle is automatically minified by webpack and esbuild.

Keep formatted JSON in your source files and config templates so humans can read and review diffs. Minify only at build time or transmission time.

Indentation: 2 Spaces vs 4 Spaces

There is no technical difference — it is purely a style preference. Two spaces is more common in JavaScript and Node.js projects. Four spaces appears in Python and some enterprise tooling. The important thing is consistency within a project. Use a linter or .editorconfig to enforce it:

# .editorconfig
[*.json]
indent_style = space
indent_size = 2

Pretty-Printing JSON in the Terminal

jq is the go-to command-line tool for formatting and querying JSON:

# Format a JSON file
cat data.json | jq .

# Format API response
curl -s https://api.example.com/data | jq .

# Extract a field
cat data.json | jq '.users[0].name'

Python also works without installing anything:

cat data.json | python3 -m json.tool

JSON vs JSON5 vs JSONC

Standard JSON is strict by design — easy to parse, no ambiguity. But config files benefit from comments and trailing commas. Two extensions address this:

  • JSONC (JSON with Comments) — used by VS Code (settings.json) and TypeScript (tsconfig.json). Supports // comments and /* block comments */.
  • JSON5 — a more permissive superset that also allows trailing commas, single-quoted strings, and unquoted keys. Less common in practice.

Standard JSON.parse() cannot parse either format — you need a dedicated parser library.

Common JSON Errors and How to Fix Them

ErrorCauseFix
Unexpected token ','Trailing commaRemove the last comma before } or ]
Unexpected token '''Single-quoted stringReplace with double quotes
Unexpected token 'u'undefined valueUse null instead — undefined is not valid JSON
Unexpected end of JSON inputMissing closing bracketCheck bracket count — every { needs a }

Formatting JSON in Code

In JavaScript, JSON.stringify() accepts a third argument for indentation:

// Minified (default)
JSON.stringify(data)

// Pretty-printed with 2 spaces
JSON.stringify(data, null, 2)

// Pretty-printed with 4 spaces
JSON.stringify(data, null, 4)

// Pretty-printed with tab characters
JSON.stringify(data, null, '\t')

In Python, use json.dumps() with the indent parameter:

import json

# Pretty-printed
print(json.dumps(data, indent=2))

# Minified
print(json.dumps(data, separators=(',', ':')))

TRY THE FREE TOOL

JSON Formatter

Format, validate & minify JSON

Open Tool →
← Back to all articles