← All articles

How to Format, Validate, Minify, and View JSON

Format and validate JSON with JavaScript, Python, jq, Prettier, VS Code, or a browser-local tool; then choose minified text, pretty output, or a tree view without silently changing the data.

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 does not change the values. It’s about making the same object readable enough to allow a person to 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 are describing the same value in JSON . Whitespace between JSON tokens is insignificant. So indentation and line breaks should not matter to a parser.

The word'should' is doing a good job there. A good formatter will preserve the JSON value; but the parser and serializer can still create edge cases if you give them duplicate keys or huge numbers, or non-JSON JavaScript values. Those are directly addressed in the sections below.

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

When debugging an API response, use a formatter that fails loudly on bad JSON.

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 via string replacement. JSON is a nested grammar . The comma in a string is not the same as the comma between array items and regex formatting will eventually fail on real input.

Format a JSON file with Node.js

For scripts, read the file as text, parse and write it, add a newline at the end so git diffs remain 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 your script is overwriting files and the input is important, write to a temp file first. This allows you to abort parsing 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 significant 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);

If you can, don’t sort keys. For human edited config files, keeping the author's groupings instead of alphabetical order may be more readable.

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.

Assuming that editor formatting has made it portable, if a server, API, database or build tool consumes the file, make sure that it is strict JSON.

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 is important when debugging. “Formatting a JSON text file is one thing. Another is serializing a live JavaScript object.

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. For almost-JSON from logs, config snippets, or LLM output, use JSON Fix to repair first and format second. The validation workflow below explains when parsing alone is insufficient.

Validate Syntax Before You Format

Parsing the input is how you start formatting, minifying and viewing. A parse that succeeds just tells you that the text is syntactically valid JSON. It does not check for required fields or correct types in an API payload.

Use three separate questions:

Layer Question Typical tool
Syntax Is this valid JSON text? JSON.parse, python -m json.tool, jq empty
Shape Are required properties and types present? JSON Schema, Ajv, Pydantic, Zod
Business rules Is this value allowed in this operation? Application code and domain checks

JavaScript syntax check:

function validateJsonSyntax(text) {
  try {
    return { valid: true, value: JSON.parse(text) };
  } catch (error) {
    return { valid: false, error: error.message };
  }
}

Command-line checks that produce a non-zero exit status on invalid input:

jq empty input.json
python3 -m json.tool input.json > /dev/null

For an API response, also check the HTTP status and content-type before parsing. A beautifully formatted login page is still HTML, not JSON. For structure validation with JSON Schema, see What is JSON?.

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 Fix 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 when converting. CSV has no native boolean, null, number, object or array type. Often, ZIP codes, product codes, account IDs, and large numeric IDs have to remain strings, even if they look numeric.

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

Minify JSON for Transport

Minification parses a JSON value and produces it without insignificant whitespace. It is the reverse of pretty printing, it is not compression and it is not encryption.

const minified = JSON.stringify(JSON.parse(raw));
minified = json.dumps(json.loads(raw), separators=(",", ":"))
jq -c . input.json

Use minified JSON if you have an embedded fixture, a request body you need to copy, or a system that requires one record per line. Keep all readable source files formatted, unless the repository intentionally stores generated minified assets.

Normally HTTP gzip or Brotli saves a lot more than just removing whitespace, because it compresses repeated property names and values. Transport compression for network performance, minify when only compact source text or record framing useful. The same duplicate-key and large-number warnings apply to minifying thru a normal JavaScript parser as to formatting.

Use a Tree View for Nested Payloads

If you are after copyable text, exact punctuation or a git diff, a formatter is best. A tree viewer is great when you need to drill down thru a vast nested payload without scrolling thru thousands of lines.

Task Best view
Edit or copy JSON text Formatter/editor
Confirm syntax Validator
Expand one branch of a large response Tree viewer
Compare two payloads Semantic JSON diff
Recover almost-JSON Repair tool, followed by validation

In a tree, verify the container type before the value: {} is an object, [] is an array, and array indexes are part of the path. A field displayed at users[2].profile.email is different from users.profile.email. Empty arrays, empty objects, null, missing properties, numeric zero, and an empty string should remain visually distinct.

Large files need moderation. Collapse irrelevant branches, search for a known key and inspect a representative record before expanding everything. A tree does not make invalid JSON valid . Fix or correct the text first , then look at the parsed result .

The JSON Viewer, JSON Validator, and JSON Diff tools run in the browser and serve different steps of the same workflow.

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?

Two spaces is common in JavaScript and web projects. Four spaces is common in some Python and Java teams. The width of the indentation is not important whitespace . So consistency is more important than the number .

Should I sort JSON keys?

Sort keys if you want stable diffs, generated fixtures, or deterministic snapshots. Do not sort keys if the existing order is significant to a human (e.g. grouping of settings in a hand-edited config file). Order of JSON arrays is significant. So formatters should not sort arrays.

Can I format JSON with comments?

Strict JSON does not allow comments. Some editor and config files use JSONC, which allows comments and trailing commas, but APIs and parsers that are expecting RFC-style JSON will reject them. Format JSONC as JSONC . Validate strict JSON before sending data to API .

Is online JSON formatting safe?

It is contingent upon where the formatting is running. The JSON Fix tool does most of the repair and formatting work in your browser, but it’s still good practice to redact sensitive values before pasting them into any web page, screenshot, issue, or chat.

Is pretty printing different from formatting JSON?

In normal JSON tooling these are the same operation: parse a value, serialize it with indentation and line breaks. Some tools call the whole editor workflow “format”, but there is no separate JSON pretty-print grammar.

Does minifying JSON compress it?

Minification removes optional white space. Compression like gzip or Brotli will encode repeated text and often reduce the transfer size even more. They can be used together but the important network optimization is HTTP compression.

When should I use a JSON tree viewer instead of a formatter?

Use a tree to navigate large nested payloads, and a formatter if you need to see exact text, edit, copy or do line-based diffs. Both need valid JSON before they can reliably display the structure.

Sources

Last reviewed August 2026.