Quick Answer
If the JSON is valid, format it to make it readable. If it is invalid, validate and fix it first. Minify only after debugging is complete. Formatting is for readability, validation is for correctness, and minification is for compact output.
Formatter vs Validator vs Minifier
| Task | Use this | Why |
|---|---|---|
| Read valid JSON | JSON Formatter | Turns one-line payloads into readable structure |
| Find syntax errors | JSON Validator | Shows exactly where the JSON breaks |
| Compress valid JSON | JSON Minifier | Removes whitespace for transport or storage |
Table summary: Use JSON Formatter when the JSON is already valid and you need readability, use JSON Validator when the payload is broken, and use JSON Minifier only after debugging is complete and you want compact output.
How to Format JSON Correctly
Formatting JSON means turning valid JSON into readable, indented text. It does not repair malformed payloads. If the input contains trailing commas, unquoted keys, single quotes, comments, or broken brackets, a strict formatter will fail until the syntax is fixed.
- Paste the payload into the JSON Validator if you suspect it is broken.
- Fix the reported syntax issue.
- Run the valid payload through the JSON Formatter for readability.
- Use the JSON Minifier only when you need compact production output.
Indentation Standards and Conventions
There is no single correct indentation for JSON, but team consistency matters more than the specific choice.
| Style | Common usage | Trade-off |
|---|---|---|
| 2 spaces | JavaScript/Node.js projects, npm package.json |
Compact, works well for deeply nested structures |
| 4 spaces | Python projects, many API documentation standards | More readable at shallow nesting depths |
| Tab | Go-adjacent tooling, personal preference | Width is viewer-configurable, but inconsistent in web displays |
The JSON.stringify() function in JavaScript accepts either a number (spaces) or a string (custom indent character) as its third argument. Python's json.dumps() accepts an indent parameter. Both default to no indentation (minified output) when omitted.
Common JSON Errors
| Error | Invalid example | Correct form |
|---|---|---|
| Trailing comma | {"a": 1,} |
{"a": 1} |
| Unquoted key | {name: "Alice"} |
{"name": "Alice"} |
| Single quotes | {'name': 'Alice'} |
{"name": "Alice"} |
| Missing comma | {"a": 1 "b": 2} |
{"a": 1, "b": 2} |
| Comments in JSON | {"a": 1 // note} |
Use strict JSON without comments |
Error summary: The most common formatter failures come from trailing commas, unquoted keys, single quotes, missing commas, and comments in otherwise JSON-like text. See the JSON Parse Errors guide for a detailed walkthrough of each error type.
When to Format and When Not to
Format JSON when you need to inspect nested data, review a payload with teammates, write documentation, or compare changes in a diff. Do not minify while you are still debugging. Do not expect a formatter to repair invalid input automatically. If the payload is failing to parse, validation comes first.
JSON in CI/CD Pipelines
Consistent JSON formatting prevents noisy diffs and merge conflicts in version-controlled config files. Integrate formatting checks into your pipeline to enforce standards automatically.
- Pre-commit hooks: Run a JSON formatter on staged
.jsonfiles before each commit. Tools likeprettierorpython -m json.toolcan normalize indentation automatically. - CI lint step: Add a check that compares each JSON file against its formatted version. If they differ, fail the build and report which files need reformatting.
- Editor configuration: Use
.editorconfigor workspace settings to set JSON indent size. This prevents inconsistencies between team members using different editors.
# Example: format-check in a CI script
for f in $(git diff --name-only --diff-filter=d HEAD~1 -- '*.json'); do
python -m json.tool "$f" > /tmp/formatted.json
diff -q "$f" /tmp/formatted.json || { echo "$f needs formatting"; exit 1; }
done
JSON5 and JSONC for Config Files
Strict JSON does not allow comments, which makes it awkward for configuration files that benefit from inline documentation. Two alternatives exist:
- JSONC: Used by VS Code, TypeScript (
tsconfig.json), and other tools. Allows//and/* */comments and trailing commas. - JSON5: A broader superset that also allows unquoted keys, single-quoted strings, and hexadecimal numbers. Used by some build tools.
If your config file supports JSONC or JSON5, use comments freely. But when sending data to APIs or storing interchange payloads, always use strict JSON. A formatter that targets strict JSON will reject JSONC input, which is the correct behavior.
Diffing Formatted JSON
Formatted JSON produces meaningful line-by-line diffs in version control. Minified JSON appears as a single changed line even when only one value changed, making code review impossible.
- Store JSON files in formatted (pretty-printed) form in version control.
- Use consistent key ordering (sorted keys) if your formatter supports it. This prevents diffs caused by key reordering rather than value changes.
- Python's
json.dumps(data, indent=2, sort_keys=True)and JavaScript's sorted-key serializers both produce deterministic output suitable for diffing.
Large JSON Handling
Formatting multi-megabyte JSON files in the browser or a text editor can cause slowdowns or crashes. Consider these strategies for large payloads:
- Streaming parsers: Tools like
jq(command line) process JSON in a streaming fashion and can format files of any size without loading the entire document into memory. - Incremental formatting: Format only the section you need to inspect. Extract a subtree with
jq '.data.users[0]'rather than formatting the entire file. - Chunked viewing: For JSON arrays with thousands of elements, many editors support folding. Collapse sections you are not inspecting to reduce render load.
- Command-line formatting:
python -m json.tool large.jsonhandles large files more reliably than browser-based tools for files over 10 MB.
Code Examples
JavaScript
const minified = '{"id":1,"name":"Alice","roles":["admin","editor"]}';
const formatted = JSON.stringify(JSON.parse(minified), null, 2);
console.log(formatted);
function safeParse(text) {
try {
return { data: JSON.parse(text), error: null };
} catch (error) {
return { data: null, error: error.message };
}
}
Python
import json
payload = '{"id":1,"name":"Alice"}'
data = json.loads(payload)
print(json.dumps(data, indent=2))
print(json.dumps(data, separators=(",", ":")))
Command Line (jq)
# Format a JSON file
jq '.' input.json > formatted.json
# Format with sorted keys
jq -S '.' input.json > sorted.json
# Extract and format a subtree
jq '.users[0].address' input.json
FAQ
Can a formatter fix broken JSON automatically?
No. Invalid JSON must be corrected before a strict formatter can pretty-print it. Use the JSON Validator to locate errors first.
What is the difference between formatting and validation?
Formatting improves readability by adding indentation and line breaks. Validation checks whether the payload is syntactically correct JSON. A formatter only works on already-valid input.
When should I minify JSON?
Minify JSON after debugging is complete and you need compact output for production transfer or storage. Never minify while actively debugging.
Does formatting change the data?
No. It only changes whitespace and line breaks, not the underlying keys, values, or structure. The parsed result is identical before and after formatting.
Should I use 2 spaces or 4 spaces for indentation?
Either works. Use 2 spaces for deeply nested structures or JavaScript-heavy projects. Use 4 spaces for Python projects or when readability at shallow depths is the priority. The key is to pick one and apply it consistently across your team.
How do I format large JSON files without crashing my editor?
Use command-line tools like jq or python -m json.tool for files over 10 MB. These process JSON without loading the entire formatted output into an editor buffer. Extract specific subtrees when you only need to inspect part of the data.
Related Tools
- JSON Formatter for readable output from valid JSON
- JSON Validator for exact syntax errors and broken payloads
- JSON Minifier for compact production output
- CSV to JSON Converter for tabular data conversion
- XML JSON Converter for legacy integration workflows
Related Guides
- Common JSON Parse Errors for a detailed walkthrough of each error type
- Data Format Conversion for CSV-to-JSON and JSON-to-CSV workflows