JSON Parse Error Explained: Common Causes and How Developers Actually Fix Them

If you've ever been debugging an API response at 2 AM, you've probably seen this:

Unexpected token } in JSON at position 124

Or the equally unhelpful:

Unexpected end of JSON input

The first time I encountered these errors, I spent twenty minutes staring at what looked like perfectly valid JSON. The problem? A single trailing comma buried deep in a nested object from a third-party API.

JSON parse errors are deceptively simple on the surface but can waste hours when you're dealing with large payloads, malformed backend responses, or dynamically generated configs. In this guide, I'll walk through the most common JSON parse errors developers actually encounter in production, explain why they happen, and share the debugging workflows that save time.


What Is a JSON Parse Error?

At its core, a JSON parse error occurs when a parser attempts to convert a JSON string into a data structure (object, array, etc.) but encounters invalid syntax.

For example:

JSON.parse('{ "name": "John", }')

This throws an error because trailing commas are not valid in JSON. Unlike JavaScript objects, which are forgiving, JSON parsers across all languages — JavaScript, Python, Go, Java, PHP, Rust — enforce strict syntax rules. Even a single misplaced character breaks parsing completely.


Why JSON Parse Errors Happen So Often

In theory, JSON is simple. In practice, it's everywhere:

  • REST API responses
  • GraphQL payloads
  • Configuration files
  • Environment variables
  • Frontend state management
  • Webhook integrations
  • Third-party service responses

Once your application starts consuming JSON from external sources or generating it dynamically, tiny syntax mistakes become nearly impossible to catch by eye. The JSON might look correct visually while still being syntactically invalid.

Common root causes include:

  • Manual editing of config files
  • API response corruption or truncation
  • Invalid escape sequences (especially Windows paths)
  • Backend returning HTML instead of JSON
  • Copy-paste errors from JavaScript objects
  • UTF-8 encoding issues
  • Mixed content types

Most Common JSON Parse Errors and How to Fix Them

1. Unexpected Token in JSON

This is hands down the most frequent error developers encounter.

Example:

JSON.parse("{ name: 'John' }")

Error:

Unexpected token n in JSON at position 2

Why It Happens

JSON has two non-negotiable rules:

  1. Keys must use double quotes
  2. String values must use double quotes

Valid JSON:

{
  "name": "John"
}

Invalid JSON (looks fine to humans):

{
  name: 'John'
}

Real Developer Scenario

This error appears constantly when developers confuse JavaScript object syntax with JSON.

JavaScript allows flexible syntax:

const user = { name: 'John', age: 30 }

But this is not valid JSON. When you copy this object into a .json file or send it as an API payload, the parser crashes immediately.

I've lost count of how many times I've seen this during code reviews — especially in test mocks and configuration files where developers manually write JSON while thinking in JavaScript.


2. Unexpected End of JSON Input

Example:

JSON.parse('{ "user": "alex" ')

Error:

Unexpected end of JSON input

Why It Happens

The parser reached the end of the string before the JSON structure was complete. This typically means:

  • Missing closing brace } or bracket ]
  • Truncated API response (network interruption)
  • Empty HTTP response body
  • Failed fetch request returning nothing

A Very Common Backend Bug

This pattern fails constantly in production:

const data = await response.json()

Why? Because the server might return:

  • An empty string
  • An HTML error page (500 Internal Server Error)
  • An authentication redirect (302 Found)
  • A truncated payload due to timeout

When this happens, response.json() throws immediately without telling you what the server actually sent back.

Safer Debugging Approach

Instead of assuming the response is valid JSON:

const text = await response.text()

console.log('Raw response:', text)

if (text) {
  try {
    const data = JSON.parse(text)
    // Process data
  } catch (err) {
    console.error('Failed to parse JSON:', err.message)
    console.error('Response was:', text.substring(0, 200))
  }
}

This simple change makes debugging infinitely easier. You can immediately see if the server returned HTML, an error message, or an incomplete payload.


3. Trailing Comma Errors

Invalid JSON:

{
  "id": 1,
  "name": "Alex",
}

Error:

Unexpected token } in JSON at position 27

JSON does not allow trailing commas. Period.

Why Developers Still Hit This Error

Modern code editors (VS Code, WebStorm, etc.) automatically format JavaScript objects with trailing commas for cleaner diffs. When developers copy those formatted objects into JSON files or API mocks, the trailing commas remain.

This becomes especially problematic in:

  • Configuration files (package.json, tsconfig.json)
  • Localization files (i18n JSON)
  • Mock API payloads for testing
  • Environment variable JSON strings

I once spent an hour debugging a CI/CD pipeline failure only to discover a trailing comma in a config.json file that had been auto-formatted by Prettier.


4. Invalid Escape Character

Broken JSON:

{
  "path": "C:\new-folder"
}

Error:

Invalid escape character

Why It Happens

Backslashes must be escaped in JSON strings. The parser interprets \n as a newline character, \t as a tab, etc. When it encounters \n in C:\new-folder, it tries to interpret it as an escape sequence and fails.

Correct version:

{
  "path": "C:\\new-folder"
}

Real Production Examples

This issue appears frequently with:

  • Windows file paths: C:\Users\DocumentsC:\\Users\\Documents
  • Regex patterns: "\d+""\\d+"
  • Generated HTML: <div class=\"test\"> needs proper escaping
  • Serialized Markdown: Backticks and special characters

Escaping problems become exponentially harder to debug once payloads are deeply nested or dynamically generated. If you're building file system APIs or working with Windows-based backends, this error will find you eventually.


5. Single Quotes Instead of Double Quotes

Invalid:

{
  'status': 'ok',
  'message': 'Success'
}

Valid:

{
  "status": "ok",
  "message": "Success"
}

Why This Keeps Happening

Because many developers manually write JSON while thinking in JavaScript syntax. JavaScript accepts both single and double quotes for strings, so the habit carries over.

This error is especially common during:

  • Quick debugging sessions
  • Test payload creation in Postman
  • API documentation writing
  • Manual config file edits

The fix is simple: always use double quotes for JSON. If you're typing JSON by hand, consider using a JSON Formatter to validate syntax instantly.


6. Comments Inside JSON

Invalid:

{
  // User information
  "name": "Alex",
  /* Additional fields */
  "email": "alex@example.com"
}

Error:

Unexpected token / in JSON at position 4

JSON does not support comments. Not single-line (//), not multi-line (/* */).

Why This Causes Confusion

Developers expect JSON to behave like:

  • JavaScript (supports comments)
  • YAML (supports # comments)
  • TypeScript configuration (supports comments via tsconfig.json extensions)
  • HJSON or JSONC (comment-enabled JSON variants)

But standard JSON is intentionally strict. Some tools (like VS Code's settings.json) allow comments internally using JSONC (JSON with Comments), which makes the behavior even more confusing across different environments.

If you need comments in configuration files, consider using YAML or adding a separate .md documentation file instead.


7. Unexpected Token < in JSON

This error is incredibly common in frontend applications consuming APIs.

Error:

Unexpected token < in JSON at position 0

What It Usually Means

The server returned HTML instead of JSON. Typically, the response starts with:

<!DOCTYPE html>
<html>
<head>...

The JSON parser sees the < character immediately and crashes.

Common Causes

  • Authentication redirects: Unauthenticated requests redirected to login page (HTML)
  • 404 pages: Invalid API endpoint returns HTML 404 page
  • Server errors: 500 Internal Server Error returns HTML error page
  • Proxy misconfiguration: Reverse proxy serving wrong content type
  • Incorrect API endpoints: Typo in URL returns HTML landing page

How Developers Usually Debug It

Instead of blindly calling:

await response.json()

Inspect the raw response first:

const text = await response.text()
console.log('Response:', text.substring(0, 500))

// Check content type
const contentType = response.headers.get('content-type')
console.log('Content-Type:', contentType)

if (contentType && contentType.includes('application/json')) {
  const data = JSON.parse(text)
  // Process data
} else {
  console.error('Expected JSON but received:', contentType)
}

That usually reveals the actual issue immediately. I've seen this exact pattern solve production bugs in under five minutes.


JSON Errors in Popular Frameworks

React

Very common mistake:

const userData = JSON.parse(props.data)

When props.data is already an object (not a string).

Result:

Unexpected token o in JSON at position 1

Because:

JSON.parse('[object Object]')

is invalid JSON. Always check the type before parsing:

if (typeof props.data === 'string') {
  const userData = JSON.parse(props.data)
} else {
  const userData = props.data // Already an object
}

Next.js

Common problems include:

  • Undefined serialization: Passing undefined to JSON.stringify() returns the string "undefined"
  • Malformed API routes: Returning HTML from API routes instead of JSON responses
  • Invalid environment variables: .env files containing malformed JSON strings

Example of broken env var:

NEXT_PUBLIC_CONFIG={"debug":true,}

That trailing comma breaks parsing immediately when you call JSON.parse(process.env.NEXT_PUBLIC_CONFIG).


Node.js

Environment variables are a major source of JSON issues. Complex configurations stored as JSON strings in .env files often contain:

  • Trailing commas
  • Single quotes
  • Unescaped backslashes
  • Missing quotes around keys

Always validate environment variable JSON before using it:

try {
  const config = JSON.parse(process.env.APP_CONFIG)
} catch (err) {
  console.error('Invalid APP_CONFIG JSON:', err.message)
  process.exit(1)
}

Practical Debugging Workflow

After debugging JSON issues repeatedly across multiple projects, most experienced developers follow roughly the same process. Here's mine:

Step 1: Inspect Raw Data

Never trust the parser error alone. The error message tells you where the problem is, but not what the problem actually is.

Inspect the raw payload first:

const text = await response.text()
console.log('Raw response:', text)

Step 2: Format the JSON

Paste the raw payload into a JSON Formatter or JSON Validator. Formatting immediately reveals:

  • Broken nesting (mismatched braces/brackets)
  • Missing commas between properties
  • Malformed arrays
  • Escaping issues
  • Trailing commas

For large payloads (1000+ lines), visual inspection is nearly impossible. A formatter highlights the exact line and column where syntax breaks.


Step 3: Validate Structure

Use strict validation instead of relying on visual inspection. Human eyes miss syntax issues surprisingly often in large payloads, especially when you've been staring at the same JSON for thirty minutes.

Online validators catch:

  • Invalid Unicode escape sequences
  • Duplicate keys
  • Invalid number formats
  • Boolean/null capitalization errors (True vs true)

Step 4: Check Encoding

UTF-8 encoding issues can silently break JSON parsing. This happens especially with:

  • Imported CSV files converted to JSON
  • Multilingual text (Chinese, Arabic, emoji)
  • External APIs with inconsistent encoding
  • Legacy systems using different character sets

Invisible characters (BOM markers, zero-width spaces) can cause parsers to fail unexpectedly. If formatting looks correct but parsing still fails, check for hidden characters.


Step 5: Validate Expected Schema

Even valid JSON may still contain incorrect structure. A payload might be syntactically correct but missing required fields or containing unexpected types.

For larger systems, combine parsing with schema validation libraries:

  • Zod: TypeScript-first schema validation
  • AJV: Fast JSON Schema validator
  • Joi: Powerful object schema description language

Example with Zod:

import { z } from 'zod'

const UserSchema = z.object({
  id: z.number(),
  name: z.string(),
  email: z.string().email()
})

try {
  const user = UserSchema.parse(JSON.parse(responseText))
  // Valid user object with correct types
} catch (err) {
  console.error('Schema validation failed:', err.errors)
}

This catches structural issues that pure JSON parsing cannot detect.


Building Your Own JSON Error Reference

One thing experienced developers eventually realize: the same JSON errors repeat constantly across projects. Keeping a small internal reference library helps teams debug faster.

Here's a quick reference table I keep bookmarked:

| Error Message | Common Cause | Quick Fix | | --- | --- | --- | | Unexpected token | Invalid syntax (quotes, commas) | Use double quotes, remove trailing commas | | Unexpected end | Truncated payload, missing } | Check network response, validate completeness | | Invalid escape | Broken backslashes | Escape backslashes: \\ | | Unexpected token < | HTML instead of JSON | Check API endpoint, auth status, content-type | | Trailing comma | JS object copied to JSON | Remove last comma in objects/arrays |

This becomes especially useful in teams working heavily with APIs, microservices, and third-party integrations. For deeper debugging strategies, check out our guide on how to fix invalid JSON.


FAQ

What is the most common JSON parse error?

The most frequent error is Unexpected token, which usually comes from invalid syntax like:

  • Using single quotes instead of double quotes
  • Leaving trailing commas
  • Forgetting quotes around keys
  • Mixing JavaScript object syntax with JSON

These errors are easy to make when manually writing JSON or copying from JavaScript code.


Why does JSON.parse fail even when the JSON looks correct?

Because tiny syntax issues are easy to miss visually. Common hidden problems include:

  • Invalid escaping: Unescaped backslashes in paths or regex
  • Invisible characters: BOM markers, zero-width spaces, non-breaking spaces
  • Encoding issues: UTF-8 vs UTF-16 mismatches
  • Incomplete payloads: Truncated responses from network timeouts
  • Mixed content: HTML error pages returned instead of JSON

Always inspect the raw response and use a formatter to highlight syntax issues.


Why does JSON require double quotes?

The JSON specification (RFC 8259) strictly requires double quotes for keys and string values. This design choice ensures:

  • Consistent parsing across all languages
  • Clear distinction from JavaScript (which allows single quotes)
  • Simpler parser implementation
  • Avoidance of ambiguity with apostrophes in text

Single quotes are valid in JavaScript objects but not in JSON.


Why do APIs sometimes return HTML instead of JSON?

Usually because of:

  • Authentication failures: Unauthenticated requests redirected to login page (HTML)
  • Proxy redirects: Reverse proxy misconfiguration serving wrong content
  • Backend crashes: Server errors returning HTML error pages (500 Internal Server Error)
  • Invalid endpoints: Typos in API URLs returning 404 HTML pages
  • Wrong content-type: Server sending text/html instead of application/json

Always check the Content-Type header and inspect raw responses when debugging API issues.


What is the fastest way to debug malformed JSON?

Most experienced developers follow this workflow:

  1. Inspect raw response: Use response.text() instead of response.json()
  2. Format the payload: Paste into a JSON formatter to highlight syntax errors
  3. Validate syntax: Use a strict validator to catch edge cases
  4. Check escaping: Look for unescaped backslashes, especially in paths
  5. Verify schema: Use schema validation (Zod, AJV) to check structure

This process usually identifies the issue within minutes, even for large payloads. For quick validation, try our online JSON tools that run entirely in your browser — no data upload, instant results.


Can JSON contain comments?

No. Standard JSON does not support comments (neither // nor /* */). This is by design to keep the format simple and universally parseable.

Some tools support JSON variants with comments:

  • JSONC (JSON with Comments): Used in VS Code settings
  • HJSON (Human JSON): Allows comments and relaxed syntax
  • JSON5: Superset of JSON with comments, trailing commas, etc.

But these are not standard JSON and won't work with strict parsers. If you need comments in configuration files, consider using YAML or maintaining separate documentation.


Final Thoughts

JSON itself is simple. Debugging malformed JSON in production systems is not.

Once payloads become large (thousands of lines), deeply nested, or dynamically generated from external APIs, parser errors stop being obvious and start becoming workflow problems. That's why experienced developers rely heavily on:

  • Formatters: To visualize structure and highlight syntax errors
  • Validators: To catch edge cases human eyes miss
  • Raw response inspection: To see what the server actually sent
  • Schema validation: To verify structure beyond syntax

If you regularly work with APIs, configuration files, webhook integrations, or third-party services, having a fast JSON formatter and validator nearby can save an enormous amount of debugging time.

Next time you hit a JSON parse error, resist the urge to stare at the payload for twenty minutes. Paste it into a formatter, check the raw response, and let the tools do the heavy lifting. You'll debug faster and with less frustration.

Try validating and formatting your JSON directly with our browser-based JSON tools — everything runs locally, no data leaves your machine, and it's usually faster than switching between multiple editors and online validators.