← All articles

How to Format JSON Safely: Pretty-Print, Sort Keys, and Avoid Data Changes

Format JSON with JSON.stringify, Python json.dumps, jq, Prettier, VS Code, or a browser-local tool, with examples for indentation, sorting keys, validation, and safe workflows.

Quick answer: if the text is already valid JSON, parse it and re-emit it with indentation. In JavaScript, use JSON.stringify(JSON.parse(raw), null, 2). In Python, use json.dumps(json.loads(raw), indent=2). On the command line, use jq . input.json or python3 -m json.tool input.json. If the input has trailing commas, single quotes, comments, or unquoted keys, repair or validate it first with JSON Fix.

Formatting JSON is not about changing values. It is about making the same object readable enough that a person can review it, diff it, paste it into a bug report, or commit it without squinting at one long line.

What JSON Formatting Actually Does

A JSON formatter parses a JSON value, then serializes it again with predictable whitespace:

  • Each object member goes on its own line.
  • Nested objects and arrays are indented.
  • Strings keep double quotes.
  • Commas stay between values, never after the last value.
  • No comments, single quotes, or JavaScript-only values are introduced.

Before formatting:

{"user":{"id":"u_123","name":"Ada","roles":["admin","editor"],"active":true}}

After formatting with 2 spaces:

{
  "user": {
    "id": "u_123",
    "name": "Ada",
    "roles": [
      "admin",
      "editor"
    ],
    "active": true
  }
}

Those two documents describe the same JSON value. Whitespace between JSON tokens is insignificant, so indentation and line breaks should not matter to a parser.

The word "should" is doing useful work there. A good formatter preserves the JSON value, but the parser and serializer can still introduce edge cases if you feed them duplicate keys, huge numbers, or non-JSON JavaScript values. The sections below call those out directly.

Pick the Right Formatting Method

Situation Use Why
Quick browser cleanup JSON Fix Repairs common broken JSON, then formats locally
JavaScript value in code JSON.stringify(value, null, 2) Built into every JS runtime
JSON text string in JavaScript JSON.stringify(JSON.parse(raw), null, 2) Validates before formatting
Python script or notebook json.dumps(data, indent=2) Built into Python
Shell pipeline or API response jq . Fast, scriptable, good errors
Machine-readable file in a repo Prettier Keeps style consistent in CI
tsconfig.json or VS Code settings VS Code / Prettier JSONC Handles comments and trailing commas in JSONC

If you are debugging an API response, use a formatter that fails loudly on invalid JSON. If you are cleaning up a hand-written config or LLM response, use a repair tool first, then review the output before trusting it.

Format JSON in JavaScript

For a JavaScript value, the formatter is JSON.stringify. The third argument controls indentation:

const value = {
  user: {
    id: 'u_123',
    name: 'Ada',
    roles: ['admin', 'editor'],
    active: true
  }
};

const pretty = JSON.stringify(value, null, 2);
console.log(pretty);

Output:

{
  "user": {
    "id": "u_123",
    "name": "Ada",
    "roles": [
      "admin",
      "editor"
    ],
    "active": true
  }
}

Use 4 for four spaces or '\t' for tabs:

JSON.stringify(value, null, 4);
JSON.stringify(value, null, '\t');

One detail people miss: the space argument is capped. Passing 100 does not create 100-space indentation; JavaScript caps numeric indentation at 10 spaces.

Format a JSON string

If you start with text, parse it first:

const raw = '{"name":"Ada","active":true}';
const formatted = JSON.stringify(JSON.parse(raw), null, 2);

console.log(formatted);

This is better than trying to add line breaks with string replacement. JSON is a nested grammar. A comma inside a string is not the same as a comma between array items, and regex-based formatting will eventually break on real input.

Format a JSON file with Node.js

For scripts, read the file as text, parse it, and write a newline at the end so Git diffs stay clean:

import { readFile, writeFile } from 'node:fs/promises';

const input = await readFile('input.json', 'utf8');
const value = JSON.parse(input);
const output = `${JSON.stringify(value, null, 2)}\n`;

await writeFile('output.json', output);

If you overwrite files in a script, write to a temporary file first when the input matters. That gives you a chance to stop if parsing fails.

Sort keys recursively in JavaScript

Sorting keys is useful for stable diffs, snapshots, and generated fixtures. It should not sort arrays, because array order is meaningful in JSON.

function sortJsonKeys(value) {
  if (Array.isArray(value)) {
    return value.map(sortJsonKeys);
  }

  if (value && typeof value === 'object' && value.constructor === Object) {
    return Object.keys(value)
      .sort((a, b) => a.localeCompare(b))
      .reduce((result, key) => {
        result[key] = sortJsonKeys(value[key]);
        return result;
      }, {});
  }

  return value;
}

const formatted = JSON.stringify(sortJsonKeys(value), null, 2);

Do not sort keys just because the option exists. For human-edited config files, preserving the author's grouping can be more readable than alphabetical order.

Format JSON in Python

Python's built-in json module has the same basic flow: load, then dump with indentation.

import json

raw = '{"name":"Ada","active":true}'
data = json.loads(raw)

print(json.dumps(data, indent=2))

Format a file:

import json

with open("input.json", encoding="utf-8") as f:
    data = json.load(f)

with open("output.json", "w", encoding="utf-8") as f:
    json.dump(data, f, indent=2)
    f.write("\n")

Sort keys:

json.dumps(data, indent=2, sort_keys=True)

Python is often a safer choice for formatting JSON that contains very large integer IDs, because Python integers are arbitrary precision. JavaScript parses JSON numbers as Number, which cannot precisely represent every 64-bit integer. If your JSON has IDs such as 9223372036854775807, keep them as strings or use a parser designed to preserve big numbers.

Format JSON on the Command Line

jq

jq pretty-prints JSON by default when you use the identity filter:

jq . input.json

Save to a separate file:

jq . input.json > output.json

Format a response from curl:

curl -s https://api.example.com/users | jq .

Sort keys:

jq --sort-keys . input.json

Minify instead of formatting:

jq -c . input.json

Avoid this common mistake:

jq . input.json > input.json

The shell opens input.json for writing before jq reads it, so you can truncate the file. Use a temporary file:

tmp="$(mktemp)"
jq . input.json > "$tmp" && mv "$tmp" input.json

Python without installing jq

If Python is already installed, json.tool is enough for basic formatting:

python3 -m json.tool input.json

From stdin:

printf '%s\n' '{"name":"Ada","active":true}' | python3 -m json.tool

Sort keys:

python3 -m json.tool --sort-keys input.json

Use four spaces:

python3 -m json.tool --indent 4 input.json

Format JSON in VS Code and Prettier

VS Code can format a .json file without an extension. Open the file and run Format Document from the command palette, or use the editor shortcut. That is fine for one file.

For a repository, use Prettier so the formatting is repeatable:

npm i -D prettier
npx prettier --write "**/*.{json,jsonc}"
npx prettier --check "**/*.{json,jsonc}"

A small config is usually enough:

{
  "tabWidth": 2,
  "trailingComma": "none"
}

Be deliberate with json vs jsonc:

  • .json should be strict JSON: no comments and no trailing commas.
  • .jsonc allows comments and trailing commas in tools that understand JSONC.
  • tsconfig.json and VS Code settings.json are commonly treated as JSONC by editors, even though they have a .json extension.
  • APIs, package metadata, lockfiles, and data feeds usually require strict JSON.

If a file is consumed by a server, API, database, or build tool, validate it as strict JSON before assuming editor formatting made it portable.

When Formatting Can Change What You See

Formatting valid JSON is supposed to preserve the value. The risky cases come from parse-and-serialize behavior:

Case What can happen Safer approach
Duplicate object keys Many parsers keep only the last value Treat duplicate keys as invalid in data contracts
Very large numbers JavaScript may round integers beyond Number.MAX_SAFE_INTEGER Quote large IDs or use a big-number-aware parser
NaN or Infinity in JS They serialize as null in arrays and object values Convert them deliberately before JSON output
undefined, functions, symbols Object properties are omitted Replace them with explicit JSON values
Date objects They become ISO strings Decide whether the API expects strings or timestamps
BigInt JSON.stringify throws Convert to string before formatting

This distinction matters in debugging. Formatting a JSON text file is one thing. Serializing a live JavaScript object is another.

Why Your JSON Will Not Format

A formatter can only format valid JSON. If parsing fails, the formatter has no structure to indent.

Common causes:

  • A trailing comma before } or ]
  • Single-quoted strings
  • Unquoted object keys
  • // or /* */ comments
  • True, False, or None from Python
  • undefined, NaN, or Infinity from JavaScript
  • A response copied with extra log text before or after the JSON
  • A truncated API response missing a closing brace or bracket

For strict syntax checking, use JSON Validator or read How to Validate JSON. For almost-JSON from logs, config snippets, or LLM output, use JSON Fix to repair first and format second.

Format JSON Online Without Uploading Your Payload

The JSON Fix tool on this site runs the core repair, validation, formatting, minifying, sorting, and copy workflow in your browser. The formatter uses the same basic model as a local script: parse the value, optionally sort object keys, then emit JSON with 2-space or 4-space indentation.

Use it this way:

  1. Paste the smallest safe sample into the input editor.
  2. Choose 2 or 4 spaces.
  3. Turn on Sort keys only when stable object order helps.
  4. Click Repair & Format for broken JSON, or Validate for strict JSON.
  5. Review repaired values before using them in an API request or config file.

Local formatting reduces exposure, but a pasted bearer token, API key, customer record, or private config is still sensitive. Redact secrets before putting them into any web page, screenshot, chat, issue, or pull request. For the deeper privacy workflow, see Why Not to Paste Sensitive JSON Online.

Convert Data to JSON, Then Format It

Some searches for "format to JSON" really mean "convert another data shape into JSON." That is a different step.

YAML to formatted JSON:

import json
import yaml

with open("config.yaml", encoding="utf-8") as f:
    data = yaml.safe_load(f)

print(json.dumps(data, indent=2))

CSV to formatted JSON:

import csv
import json

with open("users.csv", newline="", encoding="utf-8") as f:
    rows = list(csv.DictReader(f))

print(json.dumps(rows, indent=2))

Watch the types during conversion. CSV has no native number, boolean, null, object, or array type. ZIP codes, product codes, account IDs, and big numeric IDs often need to stay strings even if they look numeric.

For a fuller conversion workflow, use YAML to JSON, How to Convert JSON to CSV, or How to Convert CSV and XML to JSON.

A Practical Formatting Workflow

For one-off debugging:

  1. Format the raw JSON so you can see the shape.
  2. Check the field you actually care about.
  3. Minify again only if the destination needs one-line JSON.

For code review:

  1. Validate strict JSON.
  2. Apply the repo's formatter.
  3. Avoid sort keys unless the project already uses sorted output.
  4. Commit only the formatted data file, not unrelated generated files.

For production config:

  1. Validate syntax.
  2. Validate schema or required fields.
  3. Check large IDs and nullable fields.
  4. Keep a backup before rewriting the file in place.

Formatting makes JSON easier to read. It does not prove the payload is correct for your application.

Troubleshooting JSON Formatting

Symptom Likely cause Fix
Formatter says "Unexpected token" Input is not strict JSON Validate the line/column, then repair syntax
Output changed key order Sort keys was enabled, or the serializer re-emitted object keys Disable sorting if human grouping matters
Large ID changed JavaScript number precision loss Store the ID as a string or use a preserving parser
Comments disappeared You formatted as JSON, not JSONC Keep comments only in JSONC files
File became empty after command Redirected output to the same input file Use a temp file before mv
API rejects formatted JSON Syntax passed, but schema or business rules failed Validate required fields, types, enums, and nulls

Frequently Asked Questions

How do I format JSON in JavaScript?

Use JSON.stringify(value, null, 2) for a JavaScript value. If you have a JSON string, parse it first: JSON.stringify(JSON.parse(raw), null, 2). Parsing first confirms the text is valid JSON before you format it.

How do I format a JSON file without installing anything?

Use Python's built-in formatter: python3 -m json.tool input.json. It reads the file, validates the JSON, and prints formatted output. Add --sort-keys if you want alphabetically ordered object keys.

Does formatting JSON change the data?

Indentation and line breaks do not change JSON data. But parse-and-serialize tools can expose edge cases: duplicate keys may collapse to one value, JavaScript can round very large numbers, and non-JSON JavaScript values such as undefined cannot be represented.

Why will my JSON not format?

The input probably is not strict JSON. Common causes are trailing commas, single quotes, unquoted keys, comments, Python literals like True, JavaScript values like undefined, or a truncated response. Repair or validate the syntax first.

Should I use 2 or 4 spaces for JSON?

Use the style your project already uses. Two spaces is common in JavaScript and web projects; four spaces is common in some Python and Java teams. The indentation width is insignificant whitespace, so consistency matters more than the number.

Should I sort JSON keys?

Sort keys when you need stable diffs, generated fixtures, or deterministic snapshots. Do not sort keys when the existing order carries human meaning, such as grouped settings in a hand-edited config file. Arrays should not be sorted by a formatter because JSON array order is meaningful.

Can I format JSON with comments?

Strict JSON cannot contain comments. Some editor and config files are JSONC, which allows comments and trailing commas, but APIs and parsers that expect RFC-style JSON will reject them. Format JSONC as JSONC, and validate strict JSON before sending data to an API.

Is online JSON formatting safe?

It depends on where the formatting runs. The JSON Fix tool performs the core repair and formatting workflow in your browser, but sensitive values should still be redacted before pasting them into any web page, screenshot, issue, or chat.

Related JSON Tools and Guides

Sources

Last reviewed July 2026.