Format a file with jq
jq . data.json jq --indent 4 . data.json > pretty.json
The dot filter returns the input value. jq prints it with indentation; the second command uses four spaces and saves the output in a new file. Keep input and output filenames different. A shell opens the redirected output before jq reads, so writing back to data.json in the same command can erase the input.
With this input, {"user":{"id":42,"name":"Ada"}}, the default output is:
{
"user": {
"id": 42,
"name": "Ada"
}
}Use jq -c . data.json for compact output. That is the reverse formatting direction; the JSON Minifier provides it in the browser.
Use Python's standard library
python3 -m json.tool data.json python3 -m json.tool --indent 2 data.json pretty.json
Python's JSON command reports invalid input and exits unsuccessfully. In a Python program, use the same parser and choose an indentation width when serializing:
import json
from pathlib import Path
value = json.loads(Path("data.json").read_text(encoding="utf-8"))
Path("pretty.json").write_text(
json.dumps(value, indent=2, ensure_ascii=False) + "\n",
encoding="utf-8",
)Use JSON.stringify in JavaScript
const value = JSON.parse('{"user":{"id":42,"name":"Ada"}}');
const formatted = JSON.stringify(value, null, 2);
console.log(formatted);The third argument sets the indentation. Use 4 for four spaces or "\t" for tabs. For a file in Node.js:
import { readFileSync, writeFileSync } from "node:fs";
const value = JSON.parse(readFileSync("data.json", "utf8"));
writeFileSync("pretty.json", JSON.stringify(value, null, 2) + "\n");Handle JSON Lines as a sequence
A .jsonl or NDJSON log contains separate documents on separate lines. It is not one JSON array. jq accepts that sequence directly:
jq . events.jsonl
Indenting it produces multi-line documents, so the output is no longer JSON Lines. Use jq -c . events.jsonl if a log consumer needs one document per line. For large files, choose a streaming parser and processing strategy; a normal JSON.parse call holds the parsed document in memory.
Check precision before calling a round trip lossless
Whitespace between JSON tokens has no meaning, but parse-and-serialize tools can also normalize numbers, escape sequences and duplicate object keys. JavaScript's JSON.parse stores numbers as floating-point values. An integer identifier above Number.MAX_SAFE_INTEGER can change before formatting begins. Keep such IDs in strings or use a parser with an appropriate number representation.
If parsing fails, fix the first syntax error before formatting. The JSON error guide explains common causes, including trailing commas and HTML pasted in place of JSON.