How to Format JSON Online: A Complete Guide with Examples
Pretty-print, minify and sort JSON online or in code. Covers indentation choices, key sorting, common syntax errors and handling large files safely.
By the koducat teamUpdated 6 min read
What JSON formatting actually does
JSON formatting (also called pretty-printing or beautifying) rewrites a JSON document with consistent indentation and line breaks so humans can read it. APIs, log pipelines and build tools usually emit JSON on a single line because whitespace is wasted bytes for machines. That is fine until you need to find one field inside a 40 KB response.
A correct formatter never edits your data. It parses the text into values — objects, arrays, strings, numbers, booleans and null — and then serialises those values back to text with the whitespace you choose. Because the output is regenerated from the parsed value, formatting has a useful side effect: if the input is not valid JSON, the formatter cannot parse it and tells you where it broke.
Here is the same document before and after formatting with two-space indentation:
{"id":42,"name":"Ada","roles":["admin","editor"],"settings":{"theme":"dark","beta":false}}{
"id": 42,
"name": "Ada",
"roles": [
"admin",
"editor"
],
"settings": {
"theme": "dark",
"beta": false
}
}How to format JSON online, step by step
- Open the JSON Formatter and paste your JSON into the input panel. You can also click Sample to try it with example data first.
- Choose an indentation style: 2 spaces is the most common in JavaScript projects, 4 spaces is common in Python and Java codebases, and tabs let each reader pick their own width.
- Optionally tick Sort keys alphabetically if you want a stable order — useful before committing fixtures or comparing two documents.
- Click Format. If the JSON is valid, the formatted result appears in the output panel. If not, an error banner shows the line, the column and a caret under the problem.
- Use Tree view to collapse and expand nested objects when the document is large, then Copy or Download the result.
The formatter runs entirely in your browser, so pasting an API response that contains internal IDs does not send it anywhere. If you only need to check whether a document is valid — without changing it — the JSON Validator adds duplicate-key detection and structure statistics.
Formatting JSON in JavaScript, Python and the terminal
Every mainstream language can pretty-print JSON with its standard library. In JavaScript, the third argument of JSON.stringify sets the indentation:
const data = { id: 42, name: "Ada", roles: ["admin", "editor"] };
// Two-space indentation
console.log(JSON.stringify(data, null, 2));
// Tabs
console.log(JSON.stringify(data, null, "\t"));
// Re-format a JSON string you received as text
const pretty = JSON.stringify(JSON.parse(rawText), null, 2);Python's json module does the same with indent, and can sort keys at the same time. ensure_ascii=False keeps non-ASCII characters readable instead of escaping them as \uXXXX:
import json
with open("data.json", encoding="utf-8") as f:
data = json.load(f)
print(json.dumps(data, indent=2, sort_keys=True, ensure_ascii=False))On the command line, jq is the standard tool. If it is not installed, Python ships a formatter as a module:
# Pretty-print with jq (2-space indent by default)
jq . response.json
# Sort keys, or use tabs
jq -S . response.json
jq --tab . response.json
# Format the output of an API call
curl -s https://api.example.com/users/1 | jq .
# Without jq: Python's built-in module
python3 -m json.tool --indent 2 --sort-keys response.jsonChoosing indentation, key order and line style
Formatting choices do not change meaning, but they do change how readable your diffs are. Pick one convention per repository and apply it automatically — a formatter in your editor or a pre-commit hook avoids noisy whitespace-only changes.
| Option | What it does | When to use it |
|---|---|---|
| 2 spaces | Each nesting level is indented by two spaces | Default for JavaScript/TypeScript projects and most config files |
| 4 spaces | Each level is indented by four spaces | Teams following Python or Java style conventions |
| Tabs | One tab character per level | When readers want to choose their own indent width |
| Sorted keys | Object keys ordered alphabetically, recursively | Fixtures, snapshots and documents you plan to diff |
| Minified | All insignificant whitespace removed | Network payloads, storage, embedding JSON in other files |
Sorting keys is safe because JSON objects are unordered by definition — RFC 8259 says implementations should not depend on member order. Arrays are different: their order is meaningful, so a correct formatter never reorders array elements. To compare two documents after normalising them, use JSON Diff, which compares structure rather than text.
Common errors that stop JSON from formatting
If a formatter refuses your input, the document is not valid JSON. These are the mistakes that cause the vast majority of failures, usually because the text was hand-edited or copied from JavaScript source code:
| Error | Invalid example | Fix |
|---|---|---|
| Trailing comma | {"a": 1,} | Remove the comma after the last item |
| Single quotes | {'a': 'b'} | Use double quotes for keys and strings |
| Unquoted keys | {a: 1} | Quote every key: {"a": 1} |
| Comments | {"a": 1 // note} | Delete comments; JSON has no comment syntax |
| Missing comma | {"a": 1 "b": 2} | Add a comma between members |
| JavaScript values | {"a": undefined} | Use null, or remove the key |
| Raw line break in a string | "line one + newline | Escape it as \n |
When to minify instead of pretty-print
Minifying is the reverse operation: it strips every space and line break that is not inside a string. Pretty-printed JSON is for people; minified JSON is for machines. The size difference depends on how deeply nested the data is, so measure your own payloads rather than assuming a fixed saving.
- Pretty-print configuration files, fixtures checked into Git, documentation examples and anything a person will review.
- Minify API responses, values stored in databases or caches, JSON embedded in HTML or environment variables, and test payloads you paste into command-line tools.
- Compress, don't just minify, for network transfer: HTTP compression such as gzip or Brotli removes most of the cost of whitespace anyway, so readable JSON over a compressed connection is often fine.
The JSON Minifier shows the before and after size so you can see what you actually save. For configuration that people edit often, converting to YAML with JSON to YAML is another option, as long as the consuming tool accepts YAML.
Large files, big numbers and privacy
Browser-based formatters handle documents of several megabytes comfortably, but a few limitations apply to any JavaScript-based tool:
- Large integers lose precision. JavaScript numbers are 64-bit floats, so integers above 2^53 − 1 (9,007,199,254,740,991) are rounded when parsed. If your API uses 64-bit IDs, send them as strings.
- Duplicate keys are silently merged.
JSON.parsekeeps the last value for a repeated key. The JSON Validator reports duplicates so you can fix them at the source. - Very large files (hundreds of megabytes) are better handled with streaming tools such as
jq --streamor a language-level streaming parser, rather than loaded into a browser tab. - Secrets in payloads. Prefer tools that process data locally. Avoid pasting production credentials into any website whose processing model you have not checked.
Try it now with the free JSON Formatter & Validator — it runs in your browser.
Open JSON FormatterFrequently asked questions
Does formatting JSON change the data?
No. A formatter parses the document and writes the same values back with different whitespace. The only exceptions are lossy parser behaviours, such as rounding integers above 2^53 − 1 or keeping only the last of two duplicate keys.
Is 2-space or 4-space indentation better for JSON?
Neither is more correct. Two spaces is the most common choice in JavaScript ecosystems and keeps deeply nested data narrower; four spaces matches Python and Java style guides. Consistency within a project matters more than the choice itself.
Can I format JSON that contains comments?
Not as standard JSON. Comments are allowed in JSONC and JSON5, which some editors and config loaders accept, but strict JSON parsers reject them. Remove the comments, or use a tool that explicitly supports your dialect.
How do I format JSON in VS Code?
Open the file and run the Format Document command (Shift+Alt+F on Windows and Linux, Shift+Option+F on macOS). VS Code uses its built-in JSON formatter unless you have configured another one.