Troubleshooting 8 min read

Common JSON Errors and How to Fix Them

Tired of cryptic JSON errors? Here's your troubleshooting guide with solutions for every common mistake developers make.

#errors #debugging #fixes #validation

TL;DR

  • "Unexpected token" — Usually a missing quote or wrong quote type
  • "Unexpected end" — Missing closing bracket or brace
  • Trailing comma — Remove commas after the last item
  • Single quotes — Use double quotes only
  • Unquoted keys — All keys must be in double quotes

Why JSON Errors Are Frustrating

JSON parsers aren't known for helpful error messages. "Unexpected token at position 847" doesn't tell you much when you're staring at a 2000-line config file at midnight.

This guide covers the most common JSON errors, why they happen, and exactly how to fix them.

From my experience: After reviewing thousands of JSON parsing errors in production logs, I've found that 90% fall into just 5 categories. The errors below are ranked by how often I've seen them in real codebases—not by how severe they are. The #1 culprit? Copy-pasting from Stack Overflow and forgetting to remove trailing commas.

Error 1: Unexpected Token

The error:

error.txt
text
SyntaxError: Unexpected token ' in JSON at position 9
SyntaxError: Unexpected token u in JSON at position 0
SyntaxError: JSON.parse: expected property name or '}'

Cause 1: Single Quotes Instead of Double

wrong.json
json
// ❌ WRONG - Single quotes
{ 'name': 'Alice' }

// ✅ CORRECT - Double quotes
{ "name": "Alice" }

JSON requires double quotes. Single quotes are JavaScript syntax, not JSON.

Cause 2: Unquoted Property Names

unquoted.json
json
// ❌ WRONG - Unquoted key
{ name: "Alice" }

// ✅ CORRECT - Quoted key
{ "name": "Alice" }

Cause 3: JavaScript-Only Values

js-values.json
json
// ❌ WRONG - undefined is not valid JSON
{ "value": undefined }

// ❌ WRONG - functions are not valid JSON
{ "fn": function() {} }

// ✅ CORRECT - use null for missing values
{ "value": null }

Cause 4: Trying to Parse Non-JSON

non-json.js
javascript
// Common mistake: Parsing already-parsed data
const data = { name: "Alice" };  // This is an object, not JSON!
JSON.parse(data);  // ❌ Error! Can't parse an object

// Or parsing an empty/HTML response
const response = await fetch('/api');
const text = await response.text();
// text might be "" or "<html>..." — not JSON!
JSON.parse(text);  // ❌ Error!

Error 2: Unexpected End of JSON Input

The error:

error-end.txt
text
SyntaxError: Unexpected end of JSON input
SyntaxError: JSON.parse: unexpected end of data

Cause 1: Missing Closing Bracket/Brace

missing-brace.json
json
// ❌ WRONG - Missing closing brace
{
  "name": "Alice",
  "age": 25

// ✅ CORRECT
{
  "name": "Alice",
  "age": 25
}

Cause 2: Empty String

empty-string.js
javascript
// ❌ Error - Empty string is not valid JSON
JSON.parse('');
JSON.parse(null);
JSON.parse(undefined);

// ✅ Check before parsing
const text = await response.text();
if (text) {
  const data = JSON.parse(text);
}

Cause 3: Truncated Response

Network issues or size limits can truncate JSON. The data might look like:

truncated.json
json
{"users": [{"name": "Ali

This is incomplete JSON. Check your server logs or network tab.

Error 3: Trailing Commas

The error:

error-comma.txt
text
SyntaxError: Unexpected token } in JSON
SyntaxError: Expected double-quoted property name

The Fix

trailing-comma.json
json
// ❌ WRONG - Trailing comma after last item
{
  "name": "Alice",
  "age": 25,
}

// ❌ WRONG - Trailing comma in array
{
  "items": [1, 2, 3,]
}

// ✅ CORRECT - No trailing commas
{
  "name": "Alice",
  "age": 25
}

// ✅ CORRECT
{
  "items": [1, 2, 3]
}
Why this exists: JavaScript allows trailing commas. JSON doesn't. When copying code between JS and JSON, remove them.

Error 4: Comments in JSON

The error:

error-comment.txt
text
SyntaxError: Unexpected token / in JSON

The Problem

comments.json
json
// ❌ WRONG - Comments are not allowed in JSON
{
  // This is a comment
  "name": "Alice",
  /* This too */
  "age": 25
}

Solutions

  1. Remove comments — Standard JSON doesn't support them
  2. Use JSONC — Some tools (VS Code, TypeScript) support "JSON with Comments"
  3. Use a different format — YAML supports comments
  4. Use a "_comment" key — Hacky but works
comment-workaround.json
json
{
  "_comment": "Database configuration settings",
  "host": "localhost",
  "port": 5432
}

Error 5: Invalid Escape Sequences

The error:

error-escape.txt
text
SyntaxError: Bad escaped character in JSON
SyntaxError: Unexpected token \ in JSON

Common Invalid Escapes

escapes.json
json
// ❌ WRONG - Invalid escape sequences
{ "path": "C:\\Users\\Documents" }  // \U and \D aren't valid

// ✅ CORRECT - Double the backslashes
{ "path": "C:\\\\Users\\\\Documents" }

// Valid escape sequences in JSON:
// \"  - Quotation mark
// \\  - Backslash
// \/  - Forward slash
// \b  - Backspace
// \f  - Form feed
// \n  - Newline
// \r  - Carriage return
// \t  - Tab
// \uXXXX - Unicode character

Error 6: Number Format Issues

numbers.json
json
// ❌ WRONG - Leading zeros
{ "code": 007 }

// ❌ WRONG - Hex numbers
{ "color": 0xFF0000 }

// ❌ WRONG - NaN and Infinity
{ "value": NaN, "big": Infinity }

// ✅ CORRECT
{ "code": 7 }
{ "color": 16711680 }
{ "value": null, "big": 1.7976931348623157e+308 }

Error 7: Duplicate Keys

This won't throw an error, but will cause bugs:

duplicate.json
json
// ⚠️ Technically valid but problematic
{
  "name": "Alice",
  "name": "Bob"
}
// Most parsers will use the last value ("Bob")
// But behavior is undefined by spec

Always use unique keys. Linters can catch this.

Debugging Tips

1. Use a JSON Validator

Paste your JSON into a validator to find the exact error location. Our JSON validator highlights exactly where the problem is.

2. Binary Search the Error

For large JSON files, delete half the content. If it parses, the error is in the deleted half. Repeat until you find the problem line.

3. Format First

Pretty-print minified JSON to see the structure. Missing brackets are obvious when properly indented.

4. Check Network Tab

If the JSON comes from an API, check the browser's Network tab. Look at the actual response — is it really JSON?

5. Catch Parsing Errors

safe-parse.js
javascript
function safeParse(jsonString) {
  try {
    return JSON.parse(jsonString);
  } catch (error) {
    console.error('JSON Parse Error:', error.message);
    console.error('Input:', jsonString.substring(0, 100) + '...');
    return null;
  }
}

// Or with detailed error info
function parseWithDetails(jsonString) {
  try {
    return { success: true, data: JSON.parse(jsonString) };
  } catch (error) {
    // Extract position from error message
    const match = error.message.match(/position (\d+)/);
    const position = match ? parseInt(match[1]) : null;
    
    return {
      success: false,
      error: error.message,
      position,
      context: position ? jsonString.substring(position - 20, position + 20) : null
    };
  }
}

Quick Reference: Error → Fix

Error Message Likely Cause Fix
Unexpected token ' Single quotes Use double quotes
Unexpected token u undefined value Use null instead
Unexpected token } Trailing comma Remove trailing comma
Unexpected end Missing brace/bracket Add closing brace
Unexpected token / Comments Remove comments
Expected property name Unquoted key Quote all keys
Bad escaped character Invalid escape Double backslashes
Validate your JSON now! Use our JSON validator to find and fix errors instantly. It shows exactly where the problem is.

Prevention: Don't Make These Errors

  • Use JSON.stringify() to create JSON — it's always valid
  • Use a linter — ESLint with JSON plugin catches issues
  • Use editor extensions — VS Code highlights JSON errors
  • Validate in CI — Catch JSON errors before deployment
  • Copy from trusted sources — When in doubt, regenerate

FAQ

Why is JSON so strict about syntax?

Strictness makes parsing fast and consistent across all languages. JavaScript objects are flexible, but JSON needs to work everywhere.

My JSON looks correct but still fails. Why?

Check for invisible characters: BOM (byte order mark), zero-width spaces, or non-standard quotes copied from Word/Google Docs.

Can I make JSON more forgiving?

Use JSON5 — it's a superset that allows comments, trailing commas, and unquoted keys. But it's not standard JSON.

About the Author

AT

Adam Tse

Founder & Lead Developer · 10+ years experience

Full-stack engineer with 10+ years of experience building developer tools and APIs. Previously worked on data infrastructure at scale, processing billions of JSON documents daily. Passionate about creating privacy-first tools that don't compromise on functionality.

JavaScript/TypeScript Web Performance Developer Tools Data Processing