FORMATFORGE // KNOWLEDGE_BASE

How to Format JSON Correctly

Runs locally in your browser Updated: April 2026 No data upload required

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.

  1. Paste the payload into the JSON Validator if you suspect it is broken.
  2. Fix the reported syntax issue.
  3. Run the valid payload through the JSON Formatter for readability.
  4. 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.

# 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:

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.

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:

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

Related Guides