Debugging JSON parsing errors can feel like chasing ghosts, especially when error messages like "Unexpected token" appear. These messages rarely point to a problem with the JSON itself. Instead, they often reveal deeper issues with your request pipeline, double parsing, or malformed syntax. Here’s how to diagnose and resolve these failures efficiently.
The most common culprit: HTML masquerading as JSON
The leading cause of "Unexpected token" errors is not invalid JSON but receiving HTML instead. Servers often return HTML pages—like 404 errors, login redirects, or Cloudflare challenges—when requests fail. Your code attempts to parse this HTML as JSON, triggering the error.
A quick diagnostic involves inspecting the raw response. Use a snippet like the following to log the initial segment of the response text:
const response = await fetch(url);
const rawText = await response.text();
console.log(rawText.slice(0, 200));If the output starts with <!DOCTYPE html> or other HTML markers, the issue lies in the request itself. Verify the URL, authentication tokens, and endpoint correctness before retesting. The solution is straightforward: correct the request, not the JSON parser.
Double parsing: the silent JSON killer
Another frequent mistake occurs when JSON is parsed twice. Libraries like Fetch automatically convert the response body to JSON when using methods like .json(). If you manually parse this already-converted object again, the parser encounters [object Object] and throws an error referencing the letter 'o' at position 1.
This issue typically arises from redundant parsing steps. For example:
const response = await fetch(url);
const data = await response.json(); // First parse
const parsedData = JSON.parse(data); // Second parse — this causes the errorRemove the second parsing step to resolve the issue. The response object already contains the parsed data when using .json().
When JSON is genuinely broken: syntax mistakes to watch for
While less common, some JSON errors stem from actual syntax issues. These include:
- Trailing commas in objects or arrays:
{"key": "value",} - Unquoted keys:
{key: "value"} - Single quotes instead of double quotes:
{'key': 'value'} - Python-style literals:
TrueorNone - Missing or mismatched brackets due to truncated copy-pastes
- Comments embedded within the JSON structure (JSON does not support comments)
These errors are straightforward to diagnose with a JSON validator. Tools like JSONLint can pinpoint the exact line causing the issue. For rapid repairs, consider using a lenient parser like JSON5, which tolerates many of these common mistakes, or a repair tool that automatically converts them to valid JSON.
Fast triage: diagnose in under 10 seconds
Follow this quick decision tree to identify and resolve parsing errors:
- If the error message includes
<or HTML-like content: the server returned HTML. Fix the request URL, authentication, or server response.
- If the error references 'o' at position 1: double parsing occurred. Remove the redundant JSON.parse() call.
- For all other errors: the JSON is likely malformed. Use a validator to identify the issue, then apply targeted fixes or use a repair tool.
Proactive measures for smoother API interactions
Preventing JSON parsing errors starts with robust request handling. Always:
- Validate URLs and endpoint paths before making requests.
- Confirm authentication tokens are current and correctly formatted.
- Log raw responses during development to catch unexpected HTML or error pages early.
Additionally, integrate JSON validation into your CI pipeline to catch syntax issues before they reach production. By addressing the root causes of parsing errors, you can reduce debugging time and build more reliable integrations with APIs and data services.
AI summary
JSON parse ederken 'Beklenmeyen token' hatasıyla mı karşılaşıyorsunuz? Genellikle sorun JSON değil, yanıtın HTML olması ya da verinin iki kez parse edilmesidir. Hataların nedenlerini ve çözümlerini öğrenin.