How to Format, Validate, and Debug JSON — A Complete Guide

Learn JSON syntax rules, how to format and validate JSON in browsers and from the command line, and how to fix the most common errors.

The Quick Answer

JSON (JavaScript Object Notation) is a text format for storing and exchanging structured data. To format JSON means to add indentation and line breaks so the structure is readable. To validate JSON means to check whether it follows the syntax rules.

You can format JSON in three ways:

  1. In the browser — paste into a JSON formatter for instant results
  2. From the command line — use jq ., python -m json.tool, or Node.js
  3. In your editor — most code editors have built-in JSON formatting (VS Code: Shift+Alt+F)

The rest of this guide covers JSON syntax rules, common errors and how to fix them, formatting and minifying techniques, and command-line tools.

JSON Syntax Rules

Valid JSON follows strict rules defined in RFC 8259:

  • Data is organized in key-value pairs inside objects {} or as ordered values in arrays []
  • Keys must be strings in double quotes — no single quotes, no unquoted keys
  • Values can be: strings, numbers, booleans (true/false), null, arrays, or objects
  • No trailing commas after the last item
  • No comments — neither // nor /* */
  • No undefined — use null instead
  • Strings must use double quotes — not single quotes, not backticks

Valid JSON Example

{
  "name": "Alice",
  "age": 28,
  "isActive": true,
  "email": null,
  "skills": ["JavaScript", "Python", "SQL"],
  "address": {
    "city": "Berlin",
    "country": "Germany",
    "zip": "10115"
  }
}

JSON Data Types

Type Example Notes
String "hello world" Must use double quotes. Supports \n, \t, \", \\
Number 42, 3.14, -1, 2e10 No leading zeros. No hex/octal. Supports scientific notation
Boolean true, false Lowercase only. True and FALSE are invalid
Null null Lowercase only. Represents absence of a value
Array [1, "two", true] Ordered list. Items can be mixed types
Object {"key": "value"} Unordered key-value pairs. Keys must be strings

Common JSON Errors and How to Fix Them

These are the errors that cause the most "Unexpected token" messages. Each one is easy to fix once you know what to look for.

1. Single Quotes Instead of Double Quotes

✗  {'name': 'Alice'}
✓  {"name": "Alice"}

JSON requires double quotes for all strings — both keys and values. Single quotes are valid in JavaScript and Python but not in JSON.

2. Trailing Commas

✗  {"a": 1, "b": 2,}
✓  {"a": 1, "b": 2}

A comma after the last item is valid in JavaScript (ES5+) and many programming languages, but JSON forbids it. This is the most common copy-paste error when converting code to JSON.

3. Unquoted Keys

✗  {name: "Alice"}
✓  {"name": "Alice"}

JavaScript allows unquoted keys in objects. JSON does not — every key must be a double-quoted string.

4. Comments

✗  {"name": "Alice"} // user record
✗  {"name": "Alice", /* primary user */ "role": "admin"}
✓  {"name": "Alice", "role": "admin"}

JSON has no comment syntax. If you need comments in configuration files, use JSONC (JSON with Comments), JSON5, YAML, or TOML.

5. undefined Values

✗  {"value": undefined}
✓  {"value": null}

undefined is a JavaScript concept that does not exist in JSON. Use null to represent missing values.

6. Invisible Characters

Sometimes JSON looks correct but fails to parse. Common invisible culprits:

  • BOM (Byte Order Mark) at the start of a file — some editors add \uFEFF automatically
  • Zero-width spaces (\u200B) copied from web pages or rich text editors
  • Curly/smart quotes (" ") instead of straight quotes (") — common when copying from Word or Google Docs

Fix: Paste the JSON into a plain text editor (Notepad, nano, or a code editor) to strip hidden characters, then re-validate.

Formatting vs. Minifying

Formatting and minifying are opposite operations. Both produce valid JSON — only whitespace changes.

Formatted (Beautified)

{
  "users": [
    {
      "name": "Alice",
      "age": 28,
      "role": "admin"
    },
    {
      "name": "Bob",
      "age": 34,
      "role": "editor"
    }
  ]
}

Use when: reading, debugging, editing, code review, documentation.

Minified

{"users":[{"name":"Alice","age":28,"role":"admin"},{"name":"Bob","age":34,"role":"editor"}]}

Use when: sending API responses, storing data, embedding in URLs, reducing bandwidth.

How Much Does Minifying Save?

Minifying typically reduces JSON file size by 10–30%, depending on structure:

JSON Type Typical Savings
Flat objects (few keys) 10–15%
Deeply nested objects 20–30%
Arrays of small objects 15–25%
Already compact JSON < 5%

The savings come from removing spaces, tabs, and newlines. For large API payloads on mobile networks, even a 15% reduction measurably improves load times.

Format or Minify JSON

JSON Formatter

Paste JSON to format with 2-space or 4-space indent, or minify to remove all whitespace. Runs in your browser — nothing is sent to a server.

Open Formatter

How to Format JSON from the Command Line

Browser tools work great for quick tasks. For larger files, scripting, or CI/CD pipelines, command-line tools are more practical.

jq — The Standard JSON Tool

jq is a lightweight, fast JSON processor available on all major platforms.

Install:

# macOS
brew install jq

# Ubuntu / Debian
sudo apt install jq

# Windows (Chocolatey)
choco install jq

Format a file:

jq . input.json

# Save to a new file
jq . input.json > formatted.json

# Minify
jq -c . input.json

Extract a field:

echo '{"user": {"name": "Alice", "age": 28}}' | jq '.user.name'
# Output: "Alice"

jq can also filter arrays, transform values, and build new JSON structures — making it useful beyond simple formatting.

Python (Built-in)

Python includes a JSON formatter in its standard library. No installation required.

# Format from a file
python -m json.tool input.json

# Format from stdin (pipe)
echo '{"a":1,"b":2}' | python -m json.tool

# Format with 4-space indent (default is 2 in Python 3.13+)
python -c "import json,sys; print(json.dumps(json.load(sys.stdin),indent=4))" < input.json

# Minify
python -c "import json,sys; print(json.dumps(json.load(sys.stdin),separators=(',',':')))" < input.json

Node.js

# Format with 2-space indent
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

# Or use npx with a utility
npx json-fmt input.json

Comparison

Tool Speed Install Required Filtering Best For
jq Fast Yes Yes JSON processing, scripting, CI/CD
Python Medium Usually built-in No Quick formatting without installs
Node.js Fast Yes No JavaScript-heavy workflows
Browser tool Instant No No Quick one-off formatting

Formatting JSON in Code

If you need to format or parse JSON programmatically, here are minimal examples:

JavaScript

// Format (pretty-print)
const formatted = JSON.stringify(data, null, 2);

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

// Parse JSON text to object
const obj = JSON.parse(jsonString);

JSON.stringify accepts three arguments: the value, an optional replacer function (use null to include all), and the indentation (number of spaces or a string like "\t").

Python

import json

# Format
formatted = json.dumps(data, indent=2)

# Minify
minified = json.dumps(data, separators=(",", ":"))

# Parse
obj = json.loads(json_string)

PHP

// Format
$formatted = json_encode($data, JSON_PRETTY_PRINT);

// Minify
$minified = json_encode($data);

// Parse
$obj = json_decode($json_string, true);

Go

// Format
formatted, _ := json.MarshalIndent(data, "", "  ")

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

JSON vs. JavaScript Objects

This distinction trips up many developers. JSON is a text format. JavaScript objects are in-memory data structures.

Feature JSON JavaScript Object
Keys Must be double-quoted strings Can be unquoted
String values Double quotes only Single, double, or backtick
Trailing commas Not allowed Allowed (ES5+)
Comments Not allowed Allowed
Functions Not allowed Allowed
undefined Not allowed Allowed
NaN, Infinity Not allowed Allowed

Converting between them:

// JavaScript object → JSON text
const jsonText = JSON.stringify({ name: "Alice", age: 28 });
// '{"name":"Alice","age":28}'

// JSON text → JavaScript object
const obj = JSON.parse('{"name":"Alice","age":28}');
// { name: "Alice", age: 28 }

JSON vs. Other Data Formats

Feature JSON XML YAML TOML CSV
Readability Good Verbose Excellent Good Good (flat)
Comments No Yes Yes Yes No
Nesting Yes Yes Yes Limited No
Parsing speed Fast Slow Medium Fast Fast
Native in browsers Yes Yes (DOM) No No No
Schema support JSON Schema XSD No No No
Primary use APIs, config Legacy systems, documents Config files Config files Tabular data

When to use JSON:

  • Web APIs (the default standard)
  • Data interchange between services
  • Configuration files (when comments are not needed)
  • Storing structured data in databases (JSON columns)

When to consider alternatives:

  • YAML or TOML for configuration files that benefit from comments
  • XML for document-heavy formats or systems that require schemas
  • CSV for flat tabular data

JSONC and JSON5 — JSON with Extras

Standard JSON is strict by design. Two common extensions relax the rules for human-editable files:

JSONC (JSON with Comments)

Used by VS Code (settings.json, tsconfig.json), TypeScript, and other tools. JSONC allows:

  • // single-line comments
  • /* */ block comments
  • Trailing commas

JSONC is not valid standard JSON. It requires a JSONC-aware parser.

JSON5

A more extensive superset of JSON that allows:

  • Single and double quotes
  • Unquoted keys (if they are valid identifiers)
  • Trailing commas
  • Comments
  • Multiline strings
  • Hexadecimal numbers
  • Infinity and NaN

JSON5 is useful for configuration files written by hand. Like JSONC, it requires its own parser (json5 npm package).

Rule of thumb: Use standard JSON for data exchange between systems. Use JSONC or JSON5 only for human-editable configuration files where the consuming tool explicitly supports them.

Debugging JSON: A Step-by-Step Process

When JSON fails to parse and you cannot spot the error:

  1. Paste into a validator. A JSON formatter or validator will show the exact line and character position of the error.
  2. Check for invisible characters. Copy the JSON to a plain text editor. Look for smart quotes, BOM markers, or zero-width spaces.
  3. Search for single quotes. Find-and-replace ' with " if the JSON came from a language that uses single quotes (Python, JavaScript).
  4. Remove comments. Search for // and /* — JSON does not support them.
  5. Check for trailing commas. Search for ,} and ,] — these patterns indicate a trailing comma.
  6. Validate nested structures. Mismatched brackets are hard to spot in large JSON. A formatter with bracket highlighting makes this easier.
  7. Check encoding. JSON must be UTF-8 (or UTF-16/UTF-32 per the spec, though UTF-8 is the practical standard). If the file was saved in a different encoding, non-ASCII characters may corrupt the syntax.

Frequently Asked Questions

How do I format JSON?

Paste your JSON into a JSON formatter for instant formatting in the browser. From the command line, use jq . file.json (fastest), python -m json.tool file.json (no install needed), or your code editor's built-in formatter (VS Code: Shift+Alt+F). All of these add indentation and line breaks without changing the data.

What is the difference between formatting and minifying JSON?

Formatting adds indentation and line breaks for readability. Minifying removes all unnecessary whitespace to reduce file size. The data is identical — only whitespace changes. Format for humans; minify for machines.

Why is my JSON invalid?

The most common causes are: single quotes instead of double quotes, trailing commas, unquoted keys, comments, undefined values, and invisible characters (BOM, smart quotes, zero-width spaces). Paste the JSON into a validator to see the exact error location.

Can JSON have comments?

No. The JSON specification (RFC 8259) does not allow comments. Use JSONC (JSON with Comments) or JSON5 for configuration files that need comments. Standard JSON parsers will reject // and /* */.

What indentation should I use — 2 spaces or 4 spaces?

Both are common. 2 spaces is the default in Prettier, many JavaScript projects, and most JSON formatters. 4 spaces is common in Python. The parsed data is identical regardless of indentation. Pick one and be consistent within your project.

How do I format JSON from the command line?

Install jq and run jq . file.json. If jq is not available, use python -m json.tool file.json (Python is pre-installed on most systems). Both validate and format in one step — if the JSON is invalid, they report the error.

How do I validate JSON syntax?

Use a JSON validator or formatter. In the browser, paste your JSON and the tool will call JSON.parse() and report any errors. From the command line, jq . file.json exits with a non-zero status and error message if the JSON is invalid, making it useful in CI/CD pipelines.

What is the difference between JSON and a JavaScript object?

JSON is a text format with strict rules (double-quoted keys, no functions, no undefined, no trailing commas, no comments). JavaScript objects are in-memory data structures with looser syntax. JSON.parse() converts JSON text to a JavaScript object. JSON.stringify() converts an object to JSON text.

What is jq and why should I use it?

jq is a command-line JSON processor that can format, filter, transform, and query JSON. It is fast, lightweight, and available on all platforms. Beyond formatting, jq can extract fields (jq '.user.name'), filter arrays (jq '.[] | select(.age > 30)'), and reshape data — making it invaluable for scripting and data processing.

How much smaller is minified JSON?

Minifying typically reduces JSON size by 10–30%, depending on nesting depth. Deeply nested JSON with short keys benefits most. For API payloads, even a 15% reduction improves response times, especially on mobile connections.

What is JSON5?

JSON5 is a superset of JSON that allows single quotes, trailing commas, comments, unquoted keys, and multiline strings. It is easier to write by hand but is not valid standard JSON and requires a separate parser. Use it only for configuration files where the consuming tool supports JSON5.

How do I fix a trailing comma error?

Remove the comma after the last item in the object or array. Change {"a": 1, "b": 2,} to {"a": 1, "b": 2}. In most code editors, you can search for the regex ,\s*[}\]] to find trailing commas.

Format & Validate JSON

JSON Formatter

Paste JSON to beautify with proper indentation, minify to save space, or validate syntax. All processing happens in your browser — no data leaves your machine.

Open JSON Formatter

Related Tools

Related Tools