ToolPal
Programmer typing code in a dark IDE

How to Format JSON Online — The Complete Guide

📷 Lukas / Pexels

How to Format JSON Online — The Complete Guide

Learn how to format, validate, and clean up JSON data with a free online JSON formatter. Perfect for developers and API debugging.

DBy Daniel ParkMarch 15, 20269 min read

What Is JSON?

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write, and easy for machines to parse and generate. It is the dominant format for API responses, configuration files, and data storage in modern web development.

If you work with APIs, you encounter JSON constantly. Nearly every REST API response, every webhook payload, and every configuration file in a Node.js project is JSON. Knowing how to read, format, and debug JSON is a core developer skill.

Why Format JSON?

Minified JSON is hard to read. API responses often arrive as a single line with no whitespace — a nightmare to debug. Formatting (or "pretty-printing") JSON adds proper indentation and line breaks so you can immediately understand its structure.

Before formatting:

{"name":"John Doe","age":30,"city":"New York","hobbies":["reading","coding"],"address":{"street":"123 Main St","zip":"10001"}}

After formatting:

{
  "name": "John Doe",
  "age": 30,
  "city": "New York",
  "hobbies": [
    "reading",
    "coding"
  ],
  "address": {
    "street": "123 Main St",
    "zip": "10001"
  }
}

The difference is dramatic. In the formatted version you can see at a glance that there are five top-level keys, that hobbies is an array with two items, and that address is a nested object. In the minified version, you have to visually parse matching braces and brackets.

How to Use a JSON Formatter

  1. Paste your JSON — drop your JSON data into the input field
  2. Click "Format" — get it cleaned up with 2- or 4-space indentation
  3. Click "Minify" — compress JSON back to a single line
  4. Copy the result — one click and it is on your clipboard

The formatter validates your JSON as you paste, so you get immediate feedback if something is wrong.

Common JSON Errors (and How to Fix Them)

JSON has strict syntax rules, and violating any one of them causes a parse error. Here are the most frequent offenders, ranked by how often they appear in practice:

1. Trailing Commas

The most common JSON mistake. JavaScript allows trailing commas in arrays and objects, so developers often forget that JSON does not.

// Wrong — trailing comma after "coding"
{
  "hobbies": ["reading", "coding",]
}

// Correct
{
  "hobbies": ["reading", "coding"]
}

2. Single Quotes Instead of Double Quotes

JSON requires double quotes for all strings. Single quotes are valid in JavaScript and Python but will break JSON parsing.

// Wrong
{'name': 'John Doe'}

// Correct
{"name": "John Doe"}

3. Unquoted Keys

JavaScript objects do not need quoted keys (for simple identifiers), but in JSON every key must be a double-quoted string.

// Wrong
{name: "John Doe", age: 30}

// Correct
{"name": "John Doe", "age": 30}

4. Comments in JSON

JSON does not support comments. This surprises people because JSON looks like JavaScript, and JavaScript does support comments. If you need comments in a config file, use JSONC (JSON with Comments, supported in VS Code) or YAML.

// Wrong
{
  "port": 3000,  // server port
  "host": "localhost"
}

// Correct
{
  "port": 3000,
  "host": "localhost"
}

5. Unescaped Special Characters

Strings containing backslashes, double quotes, or control characters must be properly escaped:

// Wrong — unescaped backslash and quote
{"path": "C:\Users\john", "note": "He said "hello""}

// Correct
{"path": "C:\\Users\\john", "note": "He said \"hello\""}

6. Invalid Value Types

JSON supports exactly these value types: strings, numbers, booleans (true/false), null, objects, and arrays. Nothing else is valid:

// Wrong
{"value": undefined}
{"count": NaN}
{"total": Infinity}
{"date": new Date()}

// Correct alternatives
{"value": null}
{"count": 0}
{"total": 9999999}
{"date": "2026-03-15T10:30:00Z"}

Formatting JSON from the Command Line

When you do not have access to a web-based tool, or when you need to format JSON as part of a script, these command-line approaches are handy:

Using Python (available on most systems)

# Format a JSON file
python3 -m json.tool input.json

# Format piped JSON
curl -s https://api.example.com/data | python3 -m json.tool

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

Using jq (the Swiss Army knife for JSON)

jq is a dedicated JSON processor and the most powerful tool for working with JSON on the command line:

# Pretty-print
cat data.json | jq '.'

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

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

If you work with JSON regularly and do not have jq installed, install it now. It will save you countless hours.

Using Node.js

# Quick format
node -e "console.log(JSON.stringify(JSON.parse(require('fs').readFileSync('/dev/stdin','utf8')),null,2))" < input.json

Tips for Working with JSON

Choose Your Indentation Wisely

  • 2-space indentation: More compact, shows more content on screen. Popular in JavaScript/TypeScript projects and most web frameworks. Used in most API documentation.
  • 4-space indentation: Easier to read with deeply nested structures. Common in Python projects and enterprise Java environments.
  • Tab indentation: Technically valid but rare in JSON. Stick with spaces.

For most web development, 2 spaces is the practical choice. It provides enough visual hierarchy without wasting horizontal space.

Always Validate Before Deploying

Always validate JSON before using it in production, especially when you have written or modified it manually. A single missing comma or mismatched bracket can crash an entire application. Our formatter catches syntax errors the moment you paste, letting you spot issues quickly.

Use JSON Schema for Structural Validation

If you are building an API that accepts JSON input, simple parsing is not enough. JSON Schema lets you define the expected structure, types, and constraints:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "properties": {
    "name": { "type": "string", "minLength": 1 },
    "age": { "type": "integer", "minimum": 0 },
    "email": { "type": "string", "format": "email" }
  },
  "required": ["name", "email"]
}

This catches missing required fields, wrong types, and out-of-range values — things basic JSON parsing will never catch.

Sort Keys for Consistent Diffs

When comparing two JSON objects (in a code review or a config diff), unsorted keys create noisy diffs. Many formatters, including ours, offer an option to sort object keys alphabetically and recursively. This is especially useful for:

  • Config files in version control (reduces meaningless diffs)
  • Comparing API responses during debugging
  • Test snapshots that need to be deterministic

Real-World JSON Debugging Scenarios

Debugging an API Response

You sent a curl request and got back a single minified line of JSON. To understand what went wrong, you first need to see the structure:

curl -s https://api.example.com/users/123 | jq '.'

Or paste the response into the JSON Formatter. You can then see whether the response structure is wrong, whether a field is missing, or whether a value is unexpected.

Comparing Two JSON Objects

You have two API responses that should be identical but something differs. Format both with sorted keys, then run a diff:

jq -S '.' response1.json > sorted1.json
jq -S '.' response2.json > sorted2.json
diff sorted1.json sorted2.json

The -S flag sorts keys alphabetically so structural differences do not create noise in the diff output.

Fixing Copy-Paste Errors

A colleague pasted JSON into Slack and smart quotes mangled the content. Paste it into the formatter and it will highlight the error (curly quotes instead of straight quotes) so you know exactly what to fix.

This happens more often than you might think. Chat apps, word processors, and some text editors automatically convert " to curly quotes, which are not valid in JSON.

Extracting Data from a Large JSON File

You received a multi-megabyte JSON file but only need a small piece of it. Instead of scrolling through thousands of lines, use jq to extract exactly what you need:

# Get the email of the first user
cat users.json | jq '.data.users[0].email'

# Get all user names as a flat list
cat users.json | jq '[.data.users[].name]'

# Filter users by status
cat users.json | jq '[.data.users[] | select(.status == "active")]'

JSON vs Other Data Formats

PropertyJSONYAMLXMLTOML
ReadabilityGoodExcellentFairGood
CommentsNoYesYesYes
Data typesBasicRichString-basedRich
File sizeSmallSmallLargeSmall
Parse speedFastModerateSlowFast
EcosystemHugeLargeLargeGrowing

JSON wins for API communication and data exchange thanks to its simplicity and universal parser support. YAML is better suited for configuration files where comments and readability matter. XML still holds its ground in enterprise systems and document formats. TOML is gaining ground for configuration (Rust's Cargo, Python's pyproject.toml).

Security Considerations

Do Not Paste Sensitive Data into Server-Side Formatters

Some online JSON formatters send your data to a server for processing. If you are working with API keys, tokens, passwords, or personal data, use only a client-side formatter that processes everything in the browser. Our tool does all formatting locally — nothing is ever transmitted.

Watch Out for JSON Injection

When building applications that accept JSON input, always validate and sanitize the data. Never construct JSON by concatenating strings:

// Dangerous — JSON injection risk
const json = '{"name": "' + userInput + '"}';

// Safe
const json = JSON.stringify({ name: userInput });

Be Careful with JSON.parse on Untrusted Data

JSON.parse() is generally safe (unlike eval()), but the parsed data can have unexpected types or structure. Always validate the shape of parsed JSON before using it in your application.

Format your JSON data right now with the free JSON Formatter. It runs entirely in the browser, supports syntax highlighting, and catches errors the moment you paste.

Frequently Asked Questions

D

About the author

Daniel Park

Senior frontend engineer based in Seoul. Seven years of experience building web applications at Korean SaaS companies, with a focus on developer tooling, web performance, and privacy-first architecture. Open-source contributor to the JavaScript ecosystem and founder of ToolPal.

Learn more

Share this article

XLinkedIn

Related Posts