JSON Parse Errors: Unexpected Token & Other Messages
JSON parse errors, especially the dreaded “Unexpected token,” mean the JSON data you’re trying to read is not syntactically valid, so the parser cannot turn it into a usable object. This article explains what these errors are, why they happen, and how to fix them, with common examples and troubleshooting steps.
What Is JSON and Why Does Parsing Fail?
JSON (JavaScript Object Notation) is a lightweight data format used to exchange data between servers and web apps. It’s based on key-value pairs and ordered lists, and it must follow strict syntax rules. When a program calls JSON.parse() (in JavaScript) or a similar function in another language, it expects the input to be a perfectly formed JSON string. If anything is off—a missing comma, an extra trailing comma, a single quote instead of double, or a stray character—the parser throws an error. The most common one is SyntaxError: Unexpected token, which tells you exactly where the parser hit something it didn’t expect.
Common JSON Parse Error Messages Explained
Here are the typical error messages you’ll see and what each one means:
- Unexpected token < in JSON at position 0 – The parser found an HTML tag (like
<!DOCTYPE html>) instead of JSON. This often happens when a server returns an error page (404, 500) instead of the requested JSON. - Unexpected token } in JSON at position 10 – There’s an extra closing brace or bracket. This usually means you have mismatched curly braces or square brackets.
- Unexpected end of JSON input – The JSON string is incomplete; the parser reached the end before the structure was closed. This can happen when a network request is truncated.
- Unexpected number in JSON at position 5 – A number appears where a key, colon, or comma was expected. For example,
{"a": 1 2}. - Unexpected string in JSON at position 7 – A string appears in a place where it shouldn’t, like missing a colon between key and value.
Why Does “Unexpected Token” Happen?
The root cause is almost always invalid syntax. Here are the most common reasons:
- Single quotes instead of double quotes – JSON requires double quotes for keys and string values.
{'name': 'John'}is invalid. - Trailing commas – JSON doesn’t allow a comma after the last item in an object or array.
{"a": 1, "b": 2,}is invalid. - Unquoted keys – Keys must be in double quotes.
{name: "John"}is invalid. - Control characters in strings – Newlines, tabs, or other control characters must be escaped (e.g.,
\n). - NaN or Infinity – These are not valid JSON numbers.
{"value": NaN}is invalid. - Comments – JSON doesn’t support comments.
// commentwill cause an error. - BOM (Byte Order Mark) – A hidden Unicode character at the start of a file can cause the parser to fail at position 0.
How to Fix JSON Parse Errors
Follow these steps to diagnose and fix the issue:
- Validate the JSON – Use an online JSON validator or a browser extension. It will point to the exact line and column of the error.
- Check the response from the server – Open the browser’s developer tools (F12), go to the Network tab, and inspect the response of the failing request. If it’s an HTML error page, you know the server didn’t return JSON.
- Look for hidden characters – Copy the JSON into a text editor that shows invisible characters (like VS Code with “Render Whitespace”). Remove any BOM.
- Review your code – If you’re constructing the JSON string manually, double-check quotes, commas, and brackets. Use
JSON.stringify()to generate JSON from objects instead of hand-writing it. - Handle the error gracefully – In JavaScript, wrap
JSON.parse()in a try/catch block to log the error and the raw data for debugging.
Real-World Examples and Misconceptions
One common misconception is that JSON is the same as a JavaScript object. While they look similar, JSON is a string format with stricter rules. For instance, JavaScript allows single quotes and trailing commas, but JSON does not. Another frequent issue is when developers try to parse a JSON array directly from a file that contains multiple objects separated by newlines (NDJSON). That format is not standard JSON and requires special parsing. Also, remember that JSON.parse() expects a string; if you pass an object, it will be coerced to a string like [object Object], causing an error.
Tools and Best Practices
To avoid these errors, always use a reliable JSON library or built-in parser rather than writing your own. In JavaScript, use JSON.parse() and JSON.stringify(). In other languages, use the standard JSON module (e.g., json in Python). When fetching data from an API, always check the response status and content-type before parsing. Also, consider using schema validation (like JSON Schema) to ensure the structure is correct before parsing. For debugging, use pretty-print formatting to make the JSON readable.
Frequently Asked Questions
What does “Unexpected token < in JSON at position 0" mean?
It means the parser found a < character, which is the start of an HTML tag, instead of a valid JSON value. This usually happens when the server returns an error page (like a 404 Not Found) or a redirect page instead of the expected JSON data. Check the network response to confirm.
Can I use single quotes in JSON?
No. JSON spec requires double quotes for all strings and keys. Single quotes are allowed in JavaScript object literals, but not in JSON. If you have a JSON string with single quotes, you need to replace them with double quotes (and escape any internal double quotes).
Why does JSON.parse() fail with a valid-looking string?
Often it’s due to invisible characters like a BOM, or the string contains line breaks that are not escaped. Also, if you’re copying JSON from a console, it might be wrapped in quotes or have trailing commas. Use a validator to find the exact issue.
What is the difference between “Unexpected token” and “Unexpected end of input”?
“Unexpected token” means the parser encountered a character that doesn’t fit the expected syntax at that point. “Unexpected end of input” means the string ended before the JSON structure was complete—for example, a missing closing brace. Both indicate invalid JSON, but the latter is specifically about truncation.
How do I fix a JSON parse error in a fetch response?
First, check if the response is actually JSON by logging response.text() before parsing. If it’s HTML, the server is returning an error. If it’s JSON but still fails, validate the string. Also, ensure you’re calling response.json() only once, as the stream is consumed.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.