Skip to content
← Blog

How to Format JSON: The Complete Guide

8 min readGuides

JSON (JavaScript Object Notation) is the most widely used data interchange format on the web. Every REST API, configuration file, and NoSQL database speaks JSON. Yet formatting it correctly — with consistent indentation, valid syntax, and minimal size for production — remains a daily task that trips up developers at every level.

This guide covers everything you need to know about JSON formatting: what makes JSON valid, how to pretty-print it for readability, how to minify it for performance, and how to catch the syntax errors that waste your debugging time.

What is JSON?

JSON is a lightweight text format for structured data. It was derived from JavaScript object literal syntax but is language-independent — every modern programming language has a JSON parser. JSON is defined by RFC 8259 and uses six structural characters:

  • { and } for objects (key-value pairs)
  • [ and ] for arrays (ordered lists)
  • : separates keys from values
  • , separates elements

JSON supports four primitive types: strings (double-quoted), numbers (integer or floating-point), booleans (true / false), and null.

{
  "name": "StackCache",
  "version": 2,
  "tools": 42,
  "openSource": false,
  "description": null
}

Why Format JSON?

Unformatted JSON is a single line of text. This is efficient for machines but unreadable for humans:

{"users":[{"id":1,"name":"Alice","roles":["admin","editor"]},{"id":2,"name":"Bob","roles":["viewer"]}]}

Formatted (pretty-printed) JSON adds indentation and line breaks so you can see the structure:

{
  "users": [
    {
      "id": 1,
      "name": "Alice",
      "roles": ["admin", "editor"]
    },
    {
      "id": 2,
      "name": "Bob",
      "roles": ["viewer"]
    }
  ]
}

When to pretty-print:

  • Debugging API responses
  • Reading configuration files
  • Code reviews and documentation
  • Comparing two JSON payloads

When to minify:

  • Sending data over the network (API responses, webhooks)
  • Storing in databases or caches
  • Embedding in HTML or JavaScript bundles

Common JSON Syntax Errors

These are the mistakes that cause JSON.parse() to throw and APIs to return 400 errors:

1. Trailing commas

JSON does not allow trailing commas. JavaScript does, which is why this catches people:

// INVALID JSON
{
  "name": "Alice",
  "role": "admin",  ← trailing comma
}

Remove the comma after the last property or array element.

2. Single quotes

JSON requires double quotes for strings. Single quotes are not valid:

// INVALID JSON
{'name': 'Alice'}

// VALID JSON
{"name": "Alice"}

3. Unquoted keys

JavaScript allows unquoted object keys, but JSON does not:

// INVALID JSON
{name: "Alice"}

// VALID JSON
{"name": "Alice"}

4. Comments

JSON has no comment syntax. // and /* */ are not valid:

// INVALID JSON
{
  "debug": true  // enable debug mode
}

If you need comments in configuration, consider JSONC (JSON with Comments) or YAML, which support them natively.

5. Wrong value types

These JavaScript values are not valid in JSON:

  • undefined — use null instead
  • NaN and Infinity — use strings or null
  • Functions — not representable in JSON
  • Date objects — serialize as ISO 8601 strings

How to Format JSON in Your Browser

The fastest way to format JSON is with a browser-based tool. Paste your JSON, and it instantly validates the syntax, highlights errors with line numbers, and formats the output with your chosen indentation.

StackCache JSON Formatter runs entirely in your browser — your data never leaves your device. It supports:

  • Pretty-print with 2-space or 4-space indentation
  • Minify to remove all whitespace
  • Validate with precise error messages pointing to the exact character
  • Tree view for navigating large payloads
  • Copy formatted output to clipboard

How to Format JSON from the Command Line

Using jq

jq is the standard command-line JSON processor:

# Pretty-print
echo '{"name":"Alice"}' | jq .

# Minify
echo '{"name": "Alice"}' | jq -c .

# Format a file
jq . input.json > formatted.json

Using Python

Python's json.tool module formats JSON from the command line:

# Pretty-print
echo '{"name":"Alice"}' | python -m json.tool

# With custom indentation
python -c "import json,sys; print(json.dumps(json.load(sys.stdin), indent=4))" < input.json

Using Node.js

# Pretty-print
node -e "process.stdin.resume(); let d=''; process.stdin.on('data',c=>d+=c); process.stdin.on('end',()=>console.log(JSON.stringify(JSON.parse(d),null,2)))" < input.json

JSON Formatting in Code

JavaScript / TypeScript

// Pretty-print with 2-space indent
const formatted = JSON.stringify(data, null, 2);

// Minify
const minified = JSON.stringify(data);

// Custom replacer to filter keys
const filtered = JSON.stringify(data, ['name', 'email'], 2);

Python

import json

# Pretty-print
formatted = json.dumps(data, indent=2, ensure_ascii=False)

# Minify (remove extra whitespace)
minified = json.dumps(data, separators=(',', ':'))

# Sort keys for deterministic output
sorted_json = json.dumps(data, indent=2, sort_keys=True)

Go

// Pretty-print
formatted, _ := json.MarshalIndent(data, "", "  ")

// Minify
minified, _ := json.Marshal(data)

JSON vs Other Formats

FeatureJSONYAMLXMLTOML
Human readableGoodExcellentFairExcellent
CommentsNoYesYesYes
Data types4 primitivesRich (dates, etc.)Text onlyRich
Trailing commasNoN/AN/AYes
File sizeMediumSmallLargeSmall
Parse speedFastSlowMediumFast
Browser nativeYes (JSON.parse)NoVia DOMNo

JSON wins for API communication because every language and browser can parse it natively. YAML wins for configuration files because it supports comments and is more readable. XML wins for document markup and legacy enterprise systems. TOML wins for simple configuration with strict typing.

Best Practices

  1. Use 2-space indentation — it is the most common convention in JavaScript, TypeScript, and web development. 4-space is standard in Python.
  2. Sort keys in version-controlled files — deterministic key ordering produces clean diffs. JSON.stringify(data, null, 2) preserves insertion order; use sort_keys=True (Python) or a custom replacer to sort.
  3. Validate before deploying — a single syntax error in a JSON config file can take down a service. Always validate in CI.
  4. Minify for production APIs — removing whitespace from a typical API response reduces size by 15-30%, which matters at scale.
  5. Use a schema — JSON Schema validates structure, not just syntax. Define required fields, types, and constraints so errors are caught before runtime.

Summary

JSON formatting is a simple task with real consequences: unformatted JSON wastes debugging time, invalid JSON breaks APIs, and unminified JSON wastes bandwidth. Use pretty-print for reading, minify for sending, and always validate before deploying.

Try the JSON Formatter — it runs locally in your browser, handles files up to 10 MB, and gives you precise error messages when something is wrong.

Try it yourself

Open the tool mentioned in this guide — it runs locally in your browser, no account needed.

Open tool