Skip to content
koducathome

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:

Minified input
{"id":42,"name":"Ada","roles":["admin","editor"],"settings":{"theme":"dark","beta":false}}
Formatted output
{
  "id": 42,
  "name": "Ada",
  "roles": [
    "admin",
    "editor"
  ],
  "settings": {
    "theme": "dark",
    "beta": false
  }
}

How to format JSON online, step by step

  1. Open the JSON Formatter and paste your JSON into the input panel. You can also click Sample to try it with example data first.
  2. 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.
  3. Optionally tick Sort keys alphabetically if you want a stable order — useful before committing fixtures or comparing two documents.
  4. 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.
  5. 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.json

Choosing 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.

OptionWhat it doesWhen to use it
2 spacesEach nesting level is indented by two spacesDefault for JavaScript/TypeScript projects and most config files
4 spacesEach level is indented by four spacesTeams following Python or Java style conventions
TabsOne tab character per levelWhen readers want to choose their own indent width
Sorted keysObject keys ordered alphabetically, recursivelyFixtures, snapshots and documents you plan to diff
MinifiedAll insignificant whitespace removedNetwork 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:

ErrorInvalid exampleFix
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 + newlineEscape it as \n
The error position points at the first character the parser could not accept. With a missing comma, that is the start of the next property — so look at the end of the previous line, too. The guide How to Validate JSON covers each error in more depth.

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.parse keeps 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 --stream or 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 Formatter

Frequently 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.