All Articles

How to Format JSON: A Complete Guide

·12 min read

What is JSON?

JSON (JavaScript Object Notation) is a lightweight data-interchange format that has become the de facto standard for transmitting data between servers and web applications. Originally derived from JavaScript object syntax, JSON is language-independent and supported by virtually every modern programming language. Whether you're building a REST API, storing configuration files, or passing data between microservices, chances are you're working with JSON every day.

A typical JSON document consists of key-value pairs organized into objects (delimited by curly braces) and ordered lists of values called arrays (delimited by square brackets). Values can be strings, numbers, booleans, null, objects, or arrays — and they can be nested to arbitrary depth.

{
  "name": "DuskTools",
  "version": "2.1.0",
  "features": ["json-formatter", "base64-codec", "regex-tester"],
  "config": {
    "theme": "dark",
    "autoSave": true,
    "maxFileSize": null
  }
}

The example above is already formatted — each nested level is indented by two spaces, making the hierarchy immediately obvious. But JSON received from APIs, log files, or database exports is often a single compressed line, which is where formatting comes in.

Why Formatting JSON Matters

Unformatted (minified) JSON is compact and efficient for machines, but nearly impossible for humans to read. Consider this single-line response from an API:

{"users":[{"id":1,"name":"Alice","roles":["admin","editor"],"prefs":{"theme":"dark","lang":"en"}},{"id":2,"name":"Bob","roles":["viewer"],"prefs":{"theme":"light","lang":"fr"}}],"total":2,"page":1}

Good luck spotting a missing value or verifying the nesting structure in that blob. Formatting (also called "pretty-printing" or "beautifying") adds consistent whitespace and line breaks so you can:

JSON Syntax Rules You Must Know

Before you can format JSON, you need to know what makes it valid. Subtle syntax mistakes are the number one reason JSON formatting tools fail with cryptic errors.

Keys Must Be Double-Quoted Strings

Unlike JavaScript object literals, JSON requires every key to be wrapped in double quotes. Single quotes and unquoted keys are invalid:

// ❌ Invalid JSON
{ name: "Alice", 'age': 30 }

// ✅ Valid JSON
{ "name": "Alice", "age": 30 }

No Trailing Commas

A trailing comma after the last element in an object or array is the most common JSON error developers encounter. Many programming languages allow trailing commas, but JSON does not:

// ❌ Invalid — trailing comma
{ "name": "Alice", "age": 30, }

// ✅ Valid
{ "name": "Alice", "age": 30 }

Strings Must Use Double Quotes

String values must be enclosed in double quotes. Single quotes, backticks, and unquoted strings are all invalid in JSON.

No Comments

The JSON specification does not support comments. If you need annotated configuration files, consider JSON5, JSONC (used by VS Code), YAML, or TOML instead.

Valid Value Types Only

JSON supports exactly six value types: string, number, boolean (true/false), null, object, and array. Values like undefined, NaN, Infinity, functions, and dates are not valid JSON.

How to Format JSON Manually

While you rarely need to format JSON by hand, understanding the mechanics helps you reason about tooling and catch errors:

  1. Start at the outermost brace or bracket. Place it on its own line.
  2. For each nested level, add consistent indentation (typically 2 or 4 spaces, or one tab).
  3. Place each key-value pair on its own line. Put a space after the colon separator.
  4. Place each array element on its own line if the array contains objects or is long; short primitive arrays can stay on one line.
  5. Ensure closing braces/brackets align with the indentation of the line that opened them.

Here is the same API response from earlier, formatted with 2-space indentation:

{
  "users": [
    {
      "id": 1,
      "name": "Alice",
      "roles": ["admin", "editor"],
      "prefs": {
        "theme": "dark",
        "lang": "en"
      }
    },
    {
      "id": 2,
      "name": "Bob",
      "roles": ["viewer"],
      "prefs": {
        "theme": "light",
        "lang": "fr"
      }
    }
  ],
  "total": 2,
  "page": 1
}

Formatting JSON with Code

Every major language includes built-in JSON formatting. Here are the most common approaches:

JavaScript / Node.js

const data = { name: "Alice", scores: [95, 87, 92] };
const formatted = JSON.stringify(data, null, 2);
console.log(formatted);

The third argument to JSON.stringify controls indentation. Pass 2 for two spaces, 4 for four, or "\\t" for tabs.

Python

import json

data = {"name": "Alice", "scores": [95, 87, 92]}
formatted = json.dumps(data, indent=2, sort_keys=True)
print(formatted)

The sort_keys=True option alphabetizes keys, which helps produce consistent diffs.

Command Line with jq

# Pretty-print a JSON file
cat data.json | jq .

# Pretty-print with 4-space indent
cat data.json | jq --indent 4 .

# Extract a specific field
cat data.json | jq '.users[0].name'

jq is one of the most powerful command-line JSON processors. It formats by default and can filter, transform, and query JSON data.

Using an Online JSON Formatter

When you need to quickly inspect or clean up JSON without opening a code editor, an online formatter is the fastest option. Our JSON Formatter lets you paste raw JSON and instantly get a formatted, syntax-highlighted result. It also validates your JSON and highlights the exact line and character position of any errors.

Benefits of using an online tool:

If you frequently work with JSON API responses, keep a formatter bookmarked — it will save you hours over the course of a project.

Common JSON Errors and How to Fix Them

Unexpected Token Errors

This usually means a trailing comma, a missing comma between elements, or an unquoted key. Paste the JSON into a validator and look at the reported line number. The error is almost always on or just before that line.

Unexpected End of Input

This means you have unbalanced braces or brackets. Count your opening and closing delimiters — they must match exactly. Most code editors can highlight matching brackets to help you find the mismatch.

Invalid Unicode Escape Sequences

JSON allows Unicode escapes like \u0041 (the letter A), but malformed sequences like \u00 or \uXYZW will cause parse errors.

Number Format Issues

JSON numbers cannot have leading zeros (except 0 itself), cannot use hex notation (0xFF), and cannot include NaN or Infinity. If you need to represent these values, encode them as strings.

JSON in APIs: Request and Response Formatting

When working with REST APIs, you'll encounter JSON in both request bodies and responses. A few tips for handling JSON in API workflows:

// Safe JSON parsing in JavaScript
function safeParse(raw) {
  try {
    return { data: JSON.parse(raw), error: null };
  } catch (err) {
    return { data: null, error: err.message };
  }
}

Minification vs Beautification

Formatting and minification are opposite operations, and both have their place:

To minify JSON in JavaScript, simply call JSON.stringify(data) without the third argument. In Python, use json.dumps(data, separators=(",", ":")) to eliminate all extra whitespace.

For a typical API response, the difference can be significant. A formatted JSON payload of 10 KB might compress down to 6 KB when minified — a 40% reduction before gzip compression is even applied.

Validating JSON

Formatting a document only works if the JSON is valid to begin with. If your formatter throws an error, you need to validate and fix the raw input first. Here is a quick validation checklist:

Paste your JSON into DuskTools' JSON Formatter and it will highlight the exact position of any syntax errors, along with a human-readable explanation of what went wrong.

Converting JSON to Other Formats

Formatted JSON is often a stepping stone to other workflows. Once your JSON is clean and validated, you might want to:

Tips for Working with JSON Daily

The best developers don't memorize JSON rules — they use tools that enforce them automatically.

Wrapping Up

JSON formatting is a small skill with outsized impact on your daily productivity. Whether you use JSON.stringify in code, jq in the terminal, or a web-based tool like our JSON Formatter, the important thing is to always work with readable, validated JSON. You'll debug faster, collaborate more smoothly, and spend less time chasing phantom syntax errors.

Try These Tools

Related Articles

Enjoy this article? Buy us a coffee to support free tools and guides.