12 min read

How to Format JSON: The Complete Guide for Developers

Everything you need to know about formatting, validating, and beautifying JSON data. Includes syntax rules, common errors and fixes, code examples in multiple languages, and the best free tools.

What Is JSON Formatting and Why It Matters

JSON (JavaScript Object Notation) is the dominant data interchange format on the web. APIs return it. Configuration files use it. Databases store it. If you are a developer in 2026, you read and write JSON every single day.

The problem is that raw JSON is often unreadable. An API response arrives as a single, dense line of text with no indentation, no line breaks, and no visual hierarchy. A minified configuration file packs hundreds of nested keys into a wall of characters. Reading this without formatting is like reading a novel with no paragraphs, no chapters, and no punctuation.

JSON formatting (also called pretty-printing or beautification) is the process of adding consistent indentation, line breaks, and spacing to raw JSON so that humans can read it. A good JSON formatter takes this:

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

And transforms it into this:

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

The data is identical. The structure is now immediately clear. You can see that there are two users, Alice has two roles, and Bob is inactive. That understanding took seconds with formatting. It would have taken far longer staring at the single-line version.

Formatting matters because debugging time directly correlates with readability. When you can see the structure of your data at a glance, you find problems faster. You spot missing fields, incorrect nesting, and unexpected values before they become bugs in production.

JSON Syntax Rules: The Complete Reference

Before you can format JSON, you need to understand what valid JSON looks like. JSON supports exactly six data types, and every valid JSON document is built from these primitives.

Objects

An object is an unordered collection of key-value pairs wrapped in curly braces. Every key must be a double-quoted string. Keys and values are separated by a colon. Pairs are separated by commas.

{
  "name": "Alice",
  "age": 30,
  "email": "alice@example.com"
}

Arrays

An array is an ordered list of values wrapped in square brackets. Values are separated by commas. Arrays can contain any mix of JSON data types, including other arrays and objects.

[1, "hello", true, null, {"nested": "object"}, [1, 2, 3]]

Strings

Strings must be enclosed in double quotes. Single quotes are not valid in JSON. Special characters like newlines, tabs, and backslashes must be escaped with a backslash: \n, \t, \\. Unicode characters use the \uXXXX format.

Numbers

Numbers can be integers or floating-point. Scientific notation is supported (1.5e10). Leading zeros are not allowed (07 is invalid). NaN, Infinity, and -Infinity are not valid JSON numbers.

Booleans

Only two values: true and false. They must be lowercase. True, FALSE, and TRUE are all invalid.

Null

The null value represents an empty or missing value. It must be lowercase: null. Null, NULL, and None are all invalid in JSON.

Key Rule

JSON is stricter than JavaScript. No trailing commas, no single quotes, no comments, no undefined, no functions. Every key must be a double-quoted string. If you remember nothing else, remember this: JSON is a data format, not a programming language.

Common JSON Errors and How to Fix Them

Most JSON errors fall into a handful of categories. Learn to recognize these patterns, and you will fix 95% of JSON issues in seconds. Use a JSON validator to pinpoint the exact line and character position of any error.

1. Trailing Commas

This is the single most common JSON error. JavaScript allows a comma after the last item in an array or object. JSON does not.

// INVALID - trailing comma after "editor"
{
  "roles": ["admin", "editor",]
}

// VALID
{
  "roles": ["admin", "editor"]
}

2. Single Quotes Instead of Double Quotes

JSON requires double quotes for all strings and all property keys. Single quotes are a JavaScript convention that JSON does not support.

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

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

3. Unquoted Property Keys

In JavaScript, you can write {name: "Alice"} without quoting the key. In JSON, every key must be a double-quoted string.

// INVALID
{name: "Alice", age: 30}

// VALID
{"name": "Alice", "age": 30}

4. Comments

JSON has no comment syntax. Not //, not /* */, not #. If you need comments in a JSON-like configuration file, consider using JSONC (JSON with Comments, supported by VS Code), JSON5, or YAML instead.

// INVALID
{
  // This is a user object
  "name": "Alice"
}

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

5. Missing or Extra Brackets

Deeply nested JSON makes it easy to lose track of opening and closing brackets. The error message from your validator will point to where the parser gave up, which is usually close to the actual problem. Use a visual JSON editor with bracket matching to navigate complex structures.

6. Special Number Values

NaN, Infinity, and -Infinity are valid JavaScript but invalid JSON. If your data contains these, you need to convert them to null or a string representation before serializing to JSON.

How to Pretty-Print JSON

There are three main approaches to pretty-printing JSON, depending on your workflow and where the data lives.

Online Tools

The fastest option for one-off formatting. Paste your JSON into a browser-based tool, and get formatted output instantly. NexTool JSON Formatter processes everything client-side, so your data never leaves your browser. It adds syntax highlighting, validates your JSON, and offers both tree view and raw text output.

Command-Line Tools

For developers who live in the terminal, jq is the gold standard. It is a lightweight command-line JSON processor that can format, filter, transform, and query JSON data.

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

# Pretty-print an API response
curl -s https://api.example.com/users | jq '.'

# Pretty-print with 4-space indentation
jq --indent 4 '.' data.json

# Python built-in alternative
python -m json.tool data.json

The advantage of jq over online tools is that it handles large files efficiently and integrates into shell scripts and CI/CD pipelines. Install it with brew install jq on macOS or apt install jq on Ubuntu/Debian.

IDE and Editor Formatting

Most modern code editors can format JSON directly. In VS Code, open a .json file and press Shift + Alt + F (Windows/Linux) or Shift + Option + F (macOS). The editor will auto-indent and format the entire file. VS Code also highlights syntax errors inline with red underlines and error messages in the Problems panel.

JSON Formatting in Different Programming Languages

Every major programming language has built-in support for JSON serialization with pretty-printing options. Here is how to format JSON in the languages you are most likely to use.

JavaScript / Node.js

const data = { name: "Alice", roles: ["admin", "editor"], active: true };

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

// Pretty-print with tab indentation
const tabbed = JSON.stringify(data, null, "\t");

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

The second argument to JSON.stringify is a replacer function or array. Pass null to include all keys. The third argument is the indentation: a number for spaces, or a string (like "\t") for custom characters.

Python

import json

data = {"name": "Alice", "roles": ["admin", "editor"], "active": True}

# Pretty-print with 2-space indentation
formatted = json.dumps(data, indent=2)
print(formatted)

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

# Ensure ASCII-safe output (escape unicode)
safe = json.dumps(data, indent=2, ensure_ascii=True)

# Read and reformat a file
with open("data.json") as f:
    data = json.load(f)
with open("formatted.json", "w") as f:
    json.dump(data, f, indent=2)

PHP

$data = ["name" => "Alice", "roles" => ["admin", "editor"], "active" => true];

// Pretty-print
$formatted = json_encode($data, JSON_PRETTY_PRINT);
echo $formatted;

// Pretty-print with unescaped slashes and unicode
$clean = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

Go

import (
    "encoding/json"
    "fmt"
)

data := map[string]interface{}{
    "name": "Alice",
    "roles": []string{"admin", "editor"},
    "active": true,
}

// Pretty-print with 2-space indentation
formatted, _ := json.MarshalIndent(data, "", "  ")
fmt.Println(string(formatted))

Minification vs Beautification: When to Use Each

JSON formatting has two opposite operations, and choosing the right one depends entirely on context.

Beautification (pretty-printing) adds indentation, line breaks, and spacing. Use it when:

Minification strips all unnecessary whitespace to produce the smallest possible output. Use it when:

The difference in size is significant. A 100 KB beautified JSON file might minify to 60-70 KB. For a single API call, this is trivial. For an API serving millions of requests per day, the bandwidth savings add up fast.

Rule of Thumb

Beautify for humans, minify for machines. If a human will read the JSON, beautify it. If only software will process it, minify it. Most JSON formatting tools offer a toggle between both modes.

JSON Validation Best Practices

Formatting and validation go hand in hand. Every good JSON formatter validates your data as part of the formatting process. But validation goes beyond just checking for syntax errors. Here are the practices that prevent JSON-related bugs in production.

1. Validate Early and Often

Do not wait until your application throws an error. Validate JSON at the boundary: when you receive it from an API, when you read it from a file, when a user submits it through a form. Use a JSON viewer during development to visually confirm the structure matches your expectations.

2. Use JSON Schema for Structural Validation

Syntax validation tells you whether JSON is parseable. Schema validation tells you whether it contains the right data. JSON Schema lets you define the expected structure, required fields, data types, and value constraints. Libraries like ajv (JavaScript), jsonschema (Python), and gojsonschema (Go) can validate incoming JSON against a schema at runtime.

3. Handle Parsing Errors Gracefully

Never assume incoming JSON is valid. Wrap all JSON.parse() and equivalent calls in try-catch blocks. Log the raw input alongside the error message so you can reproduce the issue. Return a meaningful error to the caller instead of crashing silently.

// JavaScript - always wrap JSON.parse
try {
  const data = JSON.parse(rawInput);
} catch (error) {
  console.error("Invalid JSON:", error.message);
  console.error("Raw input:", rawInput.substring(0, 200));
  // Return a user-friendly error, not a stack trace
}

4. Watch for Encoding Issues

JSON must be encoded in UTF-8 (RFC 8259). If your JSON contains characters from a different encoding, parsing will fail or produce garbled output. When reading JSON from files, always specify UTF-8 encoding explicitly.

5. Test with Edge Cases

Your JSON parser and formatter should handle: empty objects ({}), empty arrays ([]), deeply nested structures (10+ levels), very long strings, unicode characters, numbers in scientific notation, and null values in unexpected positions. Use tools like NexTool JSON Editor to construct test cases visually.

Best Free JSON Formatting Tools

Here are the tools we recommend for different JSON formatting needs. All of these are free and process your data client-side in the browser.

NexTool JSON Formatter

The best all-around tool for formatting and validating JSON. Paste your JSON, get instant formatting with syntax highlighting, validation errors with line numbers, tree view, minification, and one-click copy. Zero ads, zero server-side processing. This is the tool to bookmark for daily use.

Try NexTool JSON Formatter

NexTool JSON Editor

When you need to do more than just read JSON -- edit keys, add fields, restructure nested objects -- the visual JSON editor gives you a tree-based interface alongside a raw text editor. It validates in real-time as you edit, so you never accidentally introduce syntax errors.

Try NexTool JSON Editor

NexTool JSON Viewer

Optimized for reading and exploring large JSON structures. The collapsible tree view lets you expand and collapse sections to focus on the data you care about. Search within the JSON tree to find specific keys or values without scrolling through thousands of lines.

Try NexTool JSON Viewer

NexTool JSON to CSV Converter

When you need to move JSON data into a spreadsheet or share it with non-technical team members, the JSON to CSV converter flattens nested JSON structures into tabular CSV format. It handles arrays of objects, nested keys, and mixed data types automatically.

Format Your JSON Right Now

No sign-up, no ads, no data leaving your browser. Paste your JSON and get instant formatted output with validation.

Open NexTool JSON Formatter

Frequently Asked Questions

How do I format JSON quickly?

The fastest way is to paste your JSON into a browser-based tool like NexTool JSON Formatter. It adds proper indentation and syntax highlighting instantly. For command-line users, pipe through jq: echo '{"key":"value"}' | jq '.'. In code, use JSON.stringify(data, null, 2) in JavaScript or json.dumps(data, indent=2) in Python.

What is the difference between JSON minification and beautification?

Beautification adds indentation and line breaks for human readability. Minification removes all unnecessary whitespace for the smallest possible file size. Use beautification when debugging or reading JSON. Use minification when sending JSON over a network or storing it where size matters.

Why does my JSON have a syntax error?

The most common causes are: trailing commas after the last item in an array or object, single quotes instead of double quotes, unquoted property keys, comments (JSON does not support them), and missing closing brackets or braces. Paste your JSON into a validator to see the exact line and character position of the error.

Can I format JSON in the command line?

Yes. Use jq, the standard command-line JSON processor. Install with brew install jq (macOS) or apt install jq (Linux), then run cat file.json | jq '.' for pretty-printed output. Python also includes a built-in module: python -m json.tool file.json.

Is it safe to format JSON online?

It is safe if the tool processes your data entirely in the browser (client-side). Tools like NexTool JSON Formatter never send your data to a server. You can verify this by checking the network tab in your browser's developer tools. If no data is transmitted after the page loads, the tool is client-side and safe for sensitive data.

Explore 150+ Free Developer Tools

JSON Formatter is just the start. NexTool has free tools for regex, CSV, YAML, colors, encoding, hashing, and much more.

Browse All Free Tools
NT

NexTool Team

We build free, privacy-first developer tools. Our mission is to make the tools you reach for every day faster, cleaner, and more respectful of your data.