How to Format JSON: A Step-by-Step Guide

JSON (JavaScript Object Notation) has become the de facto standard for data exchange across the internet. Whether you're working with APIs, configuration files, or data pipelines, you'll encounter JSON regularly. But raw, unformatted JSON can be difficult to read and debug. In this guide, we'll explore multiple methods to format JSON properly, from manual techniques to automated tools.

Why JSON Formatting Matters

When you receive JSON from an API or database, it's often minified—all on one line with no extra spaces or line breaks. While this saves bandwidth, it's nearly impossible to read:

{"user":{"name":"Alice","email":"alice@example.com","settings":{"notifications":true,"theme":"dark"},"age":28}}

Compare that to properly formatted JSON:

{
  "user": {
    "name": "Alice",
    "email": "alice@example.com",
    "settings": {
      "notifications": true,
      "theme": "dark"
    },
    "age": 28
  }
}

The benefits of formatting JSON are immediate:

  • Readability: You can quickly scan the structure and identify keys.
  • Debugging: Spotting errors like missing commas or mismatched braces becomes much easier.
  • Validation: Properly indented JSON reveals structural issues at a glance.
  • Documentation: Formatted JSON serves as better documentation for API responses.
  • Collaboration: Teams can review and understand data more efficiently.

Manual Formatting Steps

If you're working with small JSON snippets, manual formatting is straightforward. Here's how to do it:

Step 1: Identify the Structure

Look for opening braces { and brackets [. These signal the start of objects and arrays that need indentation.

Step 2: Add Line Breaks

Place each key-value pair or array element on its own line, starting after an opening brace or bracket.

Step 3: Apply Consistent Indentation

Use either 2 or 4 spaces (or one tab) for each nesting level. Consistency is key.

Step 4: Check Syntax

Ensure all commas are in place, closing braces match opening ones, and strings are properly quoted.

Tip: Use a text editor with JSON syntax highlighting. Most modern editors (VS Code, Sublime Text, Atom) highlight matching braces and catch syntax errors automatically.

Using Online Formatters

For quick formatting without installing tools, online JSON formatters are your best friend. They're fast, require no setup, and work directly in your browser.

SnapUtils JSON Formatter is designed specifically for developers. Simply paste your JSON, and it's instantly formatted with proper indentation, error highlighting, and validation.

Other popular online options include JSONLint, JSON.io, and BeautifyTools. Most online formatters also offer:

  • Real-time validation
  • Error detection and reporting
  • Minification options
  • Copy-to-clipboard functionality

Command-Line Tools

If you work with JSON files regularly, command-line tools provide powerful formatting options that integrate with your development workflow.

Python's json.tool Module

Python comes built-in with JSON support. Format any JSON file using:

python -m json.tool input.json > output.json

For pretty-printing to stdout:

python -m json.tool input.json

Control indentation with the --indent flag:

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

jq – The Ultimate JSON Tool

jq is a lightweight command-line JSON processor available on most Unix-based systems. It's incredibly powerful for formatting, filtering, and transforming JSON:

cat input.json | jq .

This formats the JSON with default indentation (2 spaces). To use 4-space indentation:

cat input.json | jq --indent 4 .

Format and save to a file:

jq . input.json > output.json

jq also lets you extract specific fields, filter arrays, and perform complex transformations—making it essential for JSON processing pipelines.

Using Code

When you need to format JSON programmatically, most languages provide built-in JSON libraries.

JavaScript/Node.js

The most common approach uses JSON.stringify() with an indent parameter:

const data = {"user": {"name": "Bob", "age": 30}};
const formatted = JSON.stringify(data, null, 2);
console.log(formatted);

Output:

{
  "user": {
    "name": "Bob",
    "age": 30
  }
}

The third argument specifies indentation level. Use 2 for two spaces, 4 for four spaces, or any number you prefer.

Python

Python's json module makes formatting straightforward:

import json

with open('input.json', 'r') as f:
    data = json.load(f)

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

Bash/Shell

If you have Node.js installed, use this one-liner:

node -e "console.log(JSON.stringify(JSON.parse(require('fs').readFileSync('input.json', 'utf-8')), null, 2))"

Best Practices for JSON Formatting

Indentation: 2 vs 4 Spaces

Both 2-space and 4-space indentation are valid. The choice depends on your project's conventions:

  • 2 spaces: More compact, reduces file size. Popular in JavaScript/Node.js projects.
  • 4 spaces: More readable for deeply nested structures. Common in Python and Java ecosystems.

Pick one and be consistent across your project. Most teams codify this in configuration files (.editorconfig, .prettierrc, or similar).

Readability vs File Size

Formatted JSON is human-readable but larger. Minified JSON (all on one line) saves bandwidth. The solution? Format during development, minify for production:

  • During development and debugging: Use formatted JSON for clarity.
  • In production/over the network: Use minified JSON to reduce data transfer.
  • In configuration files: Format for human review and maintenance.

Validate After Formatting

Always validate your formatted JSON to ensure it's syntactically correct. Use an online validator like SnapUtils JSON Formatter, or run it through your code:

python -m json.tool input.json

If the tool returns an error, you know there's a syntax problem.

Use Version Control Friendly Formats

When storing JSON in version control, use consistent formatting so diffs are meaningful. Avoid random spacing changes that clutter commit history.

Document Your Format Conventions

If you're working in a team, document your JSON formatting standards. Include:

  • Indentation size (2 or 4 spaces)
  • Whether to use tabs or spaces
  • How to order keys within objects
  • Whether to minify in production

Related Articles

Want to deepen your JSON knowledge? Check out these guides:

Format JSON Instantly

Stop manually formatting JSON. Use SnapUtils' fast, free JSON formatter with real-time validation and error detection.

Open JSON Formatter