·TheToolStash

How to Debug Invalid JSON: Common Errors and How to Fix Them

Learn the most common causes of invalid JSON — trailing commas, single quotes, unquoted keys, undefined values — and how to diagnose and fix them quickly.

JSON is unforgiving. One misplaced character — a trailing comma, a single quote, an unquoted key — makes the entire document invalid. Unlike JavaScript (which is liberal about what it accepts), JSON follows the precise specification in RFC 8259. Understanding what the spec allows and what it doesn't is the fastest way to debug JSON errors.

How JSON Parsing Errors Work

When a JSON parser encounters an invalid character, it stops immediately and throws an error. The error message from different environments looks different:

  • Chrome / Node.js (V8): SyntaxError: Unexpected token } in JSON at position 42
  • Firefox: SyntaxError: JSON.parse: unexpected character at line 3 column 5
  • Python: json.decoder.JSONDecodeError: Expecting ',' delimiter: line 3 column 5
The position or line number tells you exactly where to look. Paste your JSON into a validator and read the error — it will point you to the exact character that broke parsing.

The Most Common JSON Errors

1. Trailing Commas

This is the single most common JSON error for developers coming from JavaScript, where trailing commas are valid and often enforced by linters.

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

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

The same applies inside arrays:

// ❌ Invalid
["apple", "banana", "cherry",]

// ✓ Valid ["apple", "banana", "cherry"]

Fix: Remove the comma after the last item in every object and array.

2. Single Quotes

JSON requires double quotes (") for both keys and string values. Single quotes are valid in JavaScript object literals but not in JSON.

// ❌ Invalid JSON
{'name': 'Alice'}

// ✓ Valid JSON {"name": "Alice"}

Fix: Replace all single-quoted strings with double-quoted strings. In most editors: Find ' and replace with " — but be careful not to replace apostrophes inside string values.

3. Unquoted Keys

JavaScript object literals allow unquoted keys ({name: "Alice"}). JSON does not. Every key must be a quoted string.

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

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

Fix: Add double quotes around every key.

4. Comments

JSON does not support comments. Neither // line comments nor / / block comments are part of the JSON specification.

// ❌ Invalid JSON
{
  // This is the user's name
  "name": "Alice"
}

// ✓ Valid JSON { "name": "Alice" }

Fix: Strip all comments before parsing. If you need comments in config files, consider JSON5 or YAML as alternatives.

5. Undefined, NaN, and Infinity

JSON supports only six data types: strings, numbers, booleans (true/false), null, objects, and arrays. JavaScript-specific values are not valid JSON.

// ❌ Invalid JSON — these are JavaScript values, not JSON
{
  "missing": undefined,
  "ratio": NaN,
  "limit": Infinity
}

// ✓ Valid JSON { "missing": null, "ratio": null, "limit": 1.7976931348623157e+308 }

Fix: Replace undefined with null. Replace NaN and Infinity with null or a numeric fallback. In JavaScript, JSON.stringify() silently converts undefined to null in arrays and omits it from objects — which can itself cause subtle bugs.

6. Unescaped Special Characters in Strings

Inside a JSON string, certain characters must be escaped with a backslash:

| Character | Escaped form | |-----------|-------------| | " | \" | | \ | \\ | | Newline | \n | | Tab | \t | | Carriage return | \r | | Unicode | \uXXXX |

// ❌ Invalid — literal newline inside a string value
{"message": "Hello
World"}

// ✓ Valid {"message": "Hello\nWorld"}

// ❌ Invalid — unescaped quote {"quote": "She said "hello""}

// ✓ Valid {"quote": "She said \"hello\""}

Fix: Escape all control characters and double quotes inside string values.

7. Numbers in the Wrong Format

JSON numbers must be standard decimal numbers. Octal (0777), hexadecimal (0xFF), and binary (0b1010) literals are not valid JSON. Leading zeros are not allowed except for 0 itself.

// ❌ Invalid
{"hex": 0xFF, "oct": 0777, "leading": 007}

// ✓ Valid {"hex": 255, "oct": 511, "leading": 7}

Debugging Strategy

1. Use a validator with line numbers. Paste your JSON into our JSON Formatter & Validator. The error banner shows the exact message from V8, including the character position.

2. Binary search for the problem. For large JSON documents, copy the first half and validate it. If it's valid, the error is in the second half. Repeat until you've isolated the broken section.

3. Check generated JSON at its source. If your backend is generating invalid JSON, add a validation step in the serialisation layer. In Node.js: JSON.stringify(data) will throw if any value is a circular reference. In Python: json.dumps(data, ensure_ascii=False) handles Unicode correctly.

4. Handle JavaScript → JSON carefully. JSON.stringify() silently drops undefined values in objects, serialises Date objects as ISO strings, and throws on BigInt. If you're serialising objects from JavaScript, validate the output before sending it downstream.

Validating JSON in Code

// JavaScript — safe parse with error handling
function safeParseJSON(text) {
  try {
    return { data: JSON.parse(text), error: null }
  } catch (e) {
    return { data: null, error: e.message }
  }
}

const { data, error } = safeParseJSON(rawString) if (error) console.error('Invalid JSON:', error)

# Python — safe parse
import json

def safe_parse(text): try: return json.loads(text), None except json.JSONDecodeError as e: return None, f"Line {e.lineno}, col {e.colno}: {e.msg}"

data, error = safe_parse(raw_string) if error: print(f"Invalid JSON: {error}")


Validate your JSON now: Use our free JSON Formatter & Validator to instantly spot syntax errors, format your JSON with proper indentation, and explore the structure in an interactive tree view — all in your browser.

Read next: What Is Base64 Encoding? — the encoding scheme you'll find in JWT tokens, API keys, and data URIs.

Tools mentioned in this post

📋JSON Formatter
← All postsAll tools →