arrow_backBack to Blog

How to Fix JSON Parse Errors: Common Causes and Solutions

schedule5 min read

JSON parse errors are among the most frustrating bugs you will encounter. The error message is often cryptic — "Unexpected token u at position 0" — and the JSON might look perfectly fine at first glance. This guide walks through every common JSON parse error, explains what causes it, and shows you exactly how to fix it.

How JSON.parse Works

When you call JSON.parse in JavaScript, the engine reads the input string character by character and builds a native JavaScript value. If it encounters anything that does not conform to the JSON specification, it throws a SyntaxError.

The error message usually includes two pieces of information: what the parser did not expect, and where it found it. Learning to read these messages is the first step to fixing parse errors quickly.

Error: Unexpected Token

This is the most common JSON parse error. It means the parser found a character where it did not expect one.

Common causes:

  • The value is undefined or null, not a string: JSON.parse(undefined) throws "Unexpected token u"
  • Single quotes instead of double quotes: JSON.parse("{'key': 'value'}")
  • Unquoted keys: JSON.parse('{key: "value"}')
  • Trailing commas: JSON.parse('{"key": "value",}')
  • A JavaScript comment was left in: JSON.parse('{"key": "value" /* comment */}')
  • The response is HTML instead of JSON (common with API errors)

To fix it, first check what you are actually passing to JSON.parse:

console.log(typeof input, input);

If the type is not "string", you are not passing a string. If the string starts with <, you got an HTML error page instead of JSON.

Error: Unexpected End of Input

This error means the JSON string is incomplete. The parser reached the end of the string while still expecting more content.

Common causes:

  • Missing closing brace: '{"key": "value"'
  • Missing closing bracket: '[1, 2, 3'
  • An empty string was passed: JSON.parse("")
  • The response was truncated by a network error or buffer limit

The fix is to find the unclosed structure and close it. For large JSON files, use a validator that highlights the exact position of the error.

Error: Unexpected Non-Whitespace After JSON

This error means the parser successfully read one JSON value but found extra content after it.

Common cause: multiple JSON values concatenated without an array wrapper.

JSON.parse('{"a":1}{"b":2}')

This is not valid JSON. If you have multiple objects, wrap them in an array:

[{"a":1},{"b":2}]

Error: Bad Control Character in String

JSON strings cannot contain raw control characters (characters with code points 0x00 through 0x1F). If your data contains newlines, tabs, or other control characters inside a string value, they must be escaped.

Use \n for newline, \t for tab, \r for carriage return, and \uXXXX for other control characters.

Fixing Errors in API Responses

Most JSON parse errors in production come from API calls. Here is a robust pattern for handling them:

async function fetchJSON(url) { const response = await fetch(url);

if (!response.ok) { throw new Error(`HTTP ${response.status}: ${response.statusText}`); }

const text = await response.text();

try { return JSON.parse(text); } catch (error) { console.error("Invalid JSON response:", text.slice(0, 200)); throw new Error("Server returned invalid JSON"); } }

The key insight is to read the response as text first, then parse it. This lets you log the actual content when parsing fails, which makes debugging much easier.

Fixing Errors in Config Files

If a JSON config file will not parse, try these steps:

  1. Run it through a JSON validator to find the exact error location
  2. Check for trailing commas — JSON does not allow them
  3. Check for comments — JSON does not support them
  4. Make sure all keys and string values use double quotes
  5. Verify the file encoding is UTF-8 without BOM

Many editors have built-in JSON linting. Enable it to catch errors as you type.

Fixing Errors in Large Files

When the JSON file is thousands of lines, finding the error by hand is impractical. Use these strategies:

  • Use an online validator that reports the line and column number
  • Split the file into smaller chunks and validate each one
  • Use a streaming JSON parser that can report errors incrementally
  • Check the area around the reported position — the actual error is often a few characters before the reported token

Preventing Parse Errors

The best fix is prevention. Follow these practices:

  • Always use JSON.stringify to generate JSON, never manual string concatenation
  • Validate JSON at system boundaries before it enters your application
  • Use a linter or validator in your editor for JSON files
  • Add Content-Type: application/json headers to your API responses
  • Handle API errors before attempting to parse the response body
  • Use try-catch around every JSON.parse call in production code

Try It Free

Stop guessing what is wrong with your JSON. Paste it into our free JSON Validator and get instant, precise error reporting — right down to the character position. Everything runs in your browser.

Frequently Asked Questions

What does 'Unexpected token < at position 0' mean?

This almost always means the response is HTML, not JSON. The < is the start of an HTML tag like <!DOCTYPE or <html>. Check your API endpoint URL and verify the server is returning JSON with the correct Content-Type header.

Why does JSON.parse fail on a string that looks valid?

The most common hidden causes are single quotes instead of double quotes, trailing commas, unquoted keys, or invisible characters like a UTF-8 BOM at the start of the file. Use a validator that shows the exact error position to find the issue.

Can I use try-catch to handle JSON parse errors?

Yes. Always wrap JSON.parse in a try-catch block in production code. This prevents unhandled exceptions from crashing your application. Log the error and the input string (or its first few hundred characters) to make debugging easier.

build_circle

Try it yourself

Put what you learned into practice with our free json validator. 100% browser-side — your data never leaves your device.

open_in_newOpen JSON Validator

Related Articles