📖 AI Learning Gym Blog

Practical guides and tutorials for developers, creators, and curious people.

← Back to All Articles
Developer

Why JSON Formatting Matters (And How to Fix Broken JSON)

JSON is everywhere. It's how APIs return data, how configuration files are structured, and how databases like MongoDB store documents. If you work in software development, data analysis, or even just plug around with web APIs, you'll encounter JSON constantly.

Despite being designed to be simple and human-readable, JSON has strict syntax rules — and breaking any of them causes the whole thing to fail silently or throw a cryptic parse error. This guide covers what those rules are, the mistakes that trip people up most often, and how to debug broken JSON quickly.

What JSON Is and Why It Exists

JSON stands for JavaScript Object Notation. It was originally derived from JavaScript's object syntax, but it's now a language-agnostic data format used across virtually every programming language. Its appeal is simple: it's readable by humans and easy to parse by machines.

A JSON document is made up of two structures: objects (key-value pairs surrounded by curly braces) and arrays (ordered lists surrounded by square brackets). Everything else — strings, numbers, booleans, and null — are the values those structures can hold.

The Strict Rules JSON Enforces

Unlike JavaScript, JSON has no flexibility. Every rule is absolute:

  • Keys must be strings in double quotes. Single quotes are not valid. Unquoted keys are not valid.
  • String values must also use double quotes. Not single quotes.
  • No trailing commas. The last item in an object or array cannot have a comma after it.
  • No comments. JSON does not support comments of any kind — no //, no /* */.
  • Numbers must be actual numbers. Hex values, Infinity, and NaN are not valid JSON.
  • Boolean values are lowercase. true and false, not True or False.

The Most Common JSON Mistakes

1. Trailing Commas

This is probably the single most common JSON error, especially for JavaScript developers who are used to trailing commas being fine in JS objects.

// Invalid JSON — trailing comma after last item { "name": "Alice", "age": 30, ← this comma is the problem } // Valid JSON { "name": "Alice", "age": 30 }

2. Single Quotes Instead of Double Quotes

Both keys and string values must use double quotes. Single quotes will cause a parse error in any strict JSON parser.

// Invalid { 'name': 'Alice' } // Valid { "name": "Alice" }

3. Forgetting to Escape Special Characters

If a string value contains a double quote, backslash, or certain control characters, they need to be escaped with a backslash.

// Invalid — unescaped quote inside string { "message": "She said "hello" to me" } // Valid — escaped quotes { "message": "She said \"hello\" to me" }

4. Mismatched Brackets

Opening a { and closing with a ] (or vice versa) is a parse error. With deeply nested JSON this is easy to miss by eye — a formatter that shows structure visually makes it obvious.

Why Pretty-Printing Matters

JSON can be written as a single line ("minified") or spread across multiple lines with indentation ("pretty-printed"). Minified JSON is smaller and faster to transfer, but nearly impossible to read. When you're debugging an API response or editing a config file, pretty-printing makes the structure immediately clear.

Rule of thumb: Use minified JSON in production (smaller payload). Use pretty-printed JSON whenever a human needs to read or edit it. A formatter converts between the two in one click.

How to Debug JSON Fast

When you get a JSON parse error, the error message usually tells you the line and character position of the problem. Here's a reliable debugging workflow:

  1. Paste the JSON into a formatter/validator. Most will highlight the exact problem location.
  2. Check for trailing commas first — they account for a large share of JSON errors.
  3. Check that all strings use double quotes.
  4. Count your opening and closing braces and brackets — they must match.
  5. If the JSON came from an API, check whether it's actually HTML (an error page) rather than JSON. This is a common gotcha when an API call fails.

JSON vs. Related Formats

It's worth knowing where JSON fits among similar data formats:

  • YAML is more human-friendly (supports comments, less punctuation) but more error-prone due to indentation sensitivity. Common in config files (Docker, Kubernetes, GitHub Actions).
  • XML is verbose but has strong schema validation support. Still widely used in enterprise systems and certain APIs (SOAP).
  • TOML is popular for configuration files (Rust's Cargo, Python's pyproject.toml) and is very readable.
  • CSV is simpler but only handles flat, tabular data — no nesting.

For most API communication and modern web applications, JSON is the right default choice.

Frequently Asked Questions

Can I add comments to JSON?

No — standard JSON does not support comments. If you need a config file format that supports comments, consider YAML or TOML instead. Some tools like VS Code accept a variant called JSON with Comments (JSONC) for their own config files, but this is not valid standard JSON.

What's the difference between JSON.parse() and JSON.stringify()?

In JavaScript, JSON.parse() converts a JSON string into a JavaScript object. JSON.stringify() does the reverse — converts a JavaScript object into a JSON string. The second argument to stringify can control indentation: JSON.stringify(obj, null, 2) pretty-prints with 2-space indentation.

Why does my JSON validator say the file is valid but my app still fails?

The JSON might be syntactically valid but semantically wrong — the right structure but wrong data types, missing required fields, or values outside an expected range. A JSON validator only checks syntax. If you need schema validation (ensuring the data matches a specific structure), look into JSON Schema.

Paste your JSON to format, validate, and fix syntax errors — instantly, in your browser.

Open JSON Formatter →

The Six JSON Syntax Rules Every Developer Must Know

JSON has exactly six rules. Every valid JSON document follows all six. Every invalid JSON document violates at least one. Memorizing these rules is the fastest path to writing and debugging JSON confidently.

Rule 1 — Keys Must Be Strings in Double Quotes

Every key in a JSON object must be a string wrapped in double quotes. Single quotes are not valid JSON. Unquoted keys are not valid JSON. This is the most common mistake made by developers coming from JavaScript, where unquoted object keys are perfectly acceptable.

// INVALID — unquoted key
{ name: "Alice" }

// INVALID — single-quoted key
{ 'name': "Alice" }

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

Rule 2 — No Trailing Commas

JSON does not allow trailing commas — a comma after the last item in an object or array. JavaScript and most modern programming languages do allow trailing commas, which makes this rule feel unnecessary, but it is strictly enforced in all JSON parsers.

// INVALID — trailing comma after last item
{
  "name": "Alice",
  "age": 30,
}

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

Rule 3 — No Comments

JSON does not support comments of any kind — no // single-line comments and no /* */ block comments. This surprises many developers who want to annotate configuration files. If you need comments in a JSON-like config file, consider JSONC (JSON with Comments), which is supported by VS Code, or switch to YAML which natively supports comments.

Rule 4 — Values Must Be One of Six Types

JSON values must be one of exactly six types: string (in double quotes), number, boolean (true or false — lowercase only), null (lowercase), object, or array. JavaScript undefined, functions, and Date objects are not valid JSON values.

// INVALID
{ "active": True }     // Python boolean — not JSON
{ "score": None }      // Python None — not JSON
{ "value": undefined } // JavaScript undefined — not JSON

// VALID
{ "active": true }
{ "score": null }
{ "value": null }

Rule 5 — Numbers Cannot Have Leading Zeros

JSON numbers cannot have leading zeros (except for decimals like 0.5), cannot use hexadecimal notation, and cannot be Infinity or NaN.

// INVALID
{ "value": 0123 }    // leading zero
{ "value": 0xFF }    // hexadecimal
{ "value": Infinity } // Infinity

// VALID
{ "value": 123 }
{ "value": 3.14 }
{ "value": 1.5e10 }

Rule 6 — Special Characters in Strings Must Be Escaped

Certain characters must be escaped with a backslash inside JSON strings — double quotes, backslashes, and control characters like newlines and tabs.

// INVALID — unescaped double quote inside string
{ "message": "She said "hello" to him" }

// VALID
{ "message": "She said \"hello\" to him" }

// Common escape sequences:
// \"  — double quote
// \\  — backslash
// \n  — newline
// \t  — tab

The Eight Most Common JSON Errors and How to Fix Them

In practice, JSON syntax errors fall into a small set of recurring patterns. Here are the eight you will encounter most often, with examples and exact fixes.

Error 1 — Missing Comma Between Items

// INVALID — missing comma after "name" line
{
  "name": "Alice"
  "age": 30
}

// FIXED — add comma after every item except the last
{
  "name": "Alice",
  "age": 30
}

Error 2 — Trailing Comma

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

// FIXED — remove the last comma
{
  "name": "Alice",
  "age": 30
}

Error 3 — Mismatched Brackets

// INVALID — opened with { but closed with ]
{ "items": [1, 2, 3 }

// FIXED
{ "items": [1, 2, 3] }

Error 4 — Using JavaScript Values Not Valid in JSON

// INVALID
{
  "active": True,      // must be lowercase: true
  "data": undefined,   // undefined does not exist in JSON
  "date": new Date()   // Date objects are not JSON
}

// FIXED
{
  "active": true,
  "data": null,
  "date": "2026-06-15T10:30:00Z"
}

Error 5 — Single Quotes Instead of Double Quotes

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

// FIXED
{ "name": "Alice" }

Error 6 — Comments in JSON

// INVALID — JSON does not support comments
{
  "name": "Alice",  // this is the user's name
  "age": 30         /* age in years */
}

// FIXED — remove all comments
{
  "name": "Alice",
  "age": 30
}

Error 7 — Unescaped Special Characters in Strings

// INVALID
{ "path": "C:\Users\Alice" }  // backslash not escaped
{ "quote": "He said "hello"" } // quote not escaped

// FIXED
{ "path": "C:\\Users\\Alice" }
{ "quote": "He said \"hello\"" }

Error 8 — Empty or Whitespace-Only Input

An empty string is not valid JSON. Valid JSON must be either an object {}, an array [], a string "", a number, a boolean, or null. An empty input will always fail to parse.

How to Debug JSON Errors Fast

When you receive a JSON parse error, follow this systematic process to find and fix the problem quickly without reading every character manually.

Step 1 — Beautify First, Then Read

Never try to read or debug raw minified JSON. Paste it into a formatter tool first. Beautified JSON with proper indentation makes the structure immediately visible — mismatched brackets, missing commas, and structural errors become obvious within seconds.

Step 2 — Read the Error Message Carefully

JSON parse error messages typically include a line number and character position — "Unexpected token at position 47" or "Expected property name at line 3 column 12." Go to that exact location. The error is almost always at or just before the reported position.

Step 3 — Check the Four Most Common Problems First

  • Are there trailing commas anywhere in the document?
  • Are all keys wrapped in double quotes?
  • Do all opening brackets and braces have matching closing ones?
  • Are all string values using double quotes, not single quotes?

Step 4 — Validate Programmatically in JavaScript

try {
  const data = JSON.parse(jsonString);
  console.log('Valid JSON:', data);
} catch (error) {
  console.error('Parse error:', error.message);
  console.log('Attempted to parse:', jsonString);
}

Step 5 — Use jq on the Command Line

# Validate and pretty-print a JSON file
cat data.json | jq .

# Minify JSON
cat data.json | jq -c .

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

Pretty-Print vs Minified JSON — When to Use Each

When to Use Pretty-Printed JSON

  • Writing configuration files that humans will read and edit
  • Debugging API responses or inspecting data structures
  • Storing data in version-controlled files where readable diffs matter
  • Generating output intended for human review or documentation

When to Use Minified JSON

  • Transmitting data over a network where bandwidth matters
  • Storing JSON in databases or caches where storage size is a concern
  • Including JSON in HTTP responses from production APIs
  • Generating JSON for machine consumption where human readability is irrelevant

How to Toggle Between Formats in Code

// JavaScript
JSON.stringify(data, null, 2);  // pretty-print with 2-space indent
JSON.stringify(data);           // minify

// Python
import json
json.dumps(data, indent=2)                        # pretty-print
json.dumps(data, separators=(',', ':'))            # minify

Best practice: develop and debug with pretty-printed JSON. Deploy and transmit minified JSON. Most JSON libraries toggle between the two with a single parameter change.