JSON Parse Failed: 10 Common API Errors and How to Debug Them
🚀 Validate your JSON first:
In frontend and backend development, "JSON parse failed" is one of the most common errors: your code expects a JSON response, but JSON.parse throws an exception and the console fills with red errors.
This article breaks down 10 typical JSON parsing errors from real-world debugging scenarios, and provides actionable troubleshooting steps and prevention tips to help you quickly locate and fix the root cause.
If you have a "parse failed" JSON sample on hand, paste it into the JSON Editor to automatically check syntax and highlight the exact error position.
Overview of Typical Error Messages
Across different environments and scenarios, you might see errors like:
SyntaxError: Unexpected token ':' in JSON at position 3SyntaxError: Unexpected token '<' in JSON at position 0SyntaxError: Unexpected token 'u' in JSON at position 20SyntaxError: Unexpected token '/' in JSON at position 2JSONParseError: Unexpected end of JSON input
These all mean: the input is not valid JSON, but the underlying reasons can be very different: format errors, HTML error pages, encoding issues, truncated responses, and more.
Below, we break them down by scenario.
Scenario 1: Backend Returns an HTML Error Page (500/404)
Symptoms
- Your frontend calls an API expecting JSON.
- The actual status code is 500/404/503, and the body is an HTML error page.
- The frontend still calls
JSON.parse(responseText)and fails with:
SyntaxError: Unexpected token '<' in JSON at position 0
Cause
HTML usually starts with <!DOCTYPE html> or <html>, so the first character is <, which is not valid JSON.
Debugging Steps
- Open the browser's Network panel and find the request.
- Check the Status code: is it 2xx?
- Check
Content-Typein Response Headers:- Is it
application/json? - Or
text/html/text/plain?
- Is it
- Inspect the Response Body: is it an HTML error page?
Solutions
- Before calling
JSON.parseon the frontend:- Check that the status code is 2xx;
- Check that
Content-Typeincludesapplication/json.
- For non-2xx responses, prioritize showing error information (e.g.,
error.message) instead of trying to parse JSON.
Scenario 2: Content-Type Is Not application/json
Symptoms
- The response body "looks like JSON", but
Content-Typeistext/htmlortext/plain. - Some frameworks/middleware refuse to auto-parse, or your code hesitates to safely call
JSON.parse.
Causes
- Backend framework configuration (e.g., defaulting to
text/html). - Reverse proxy/gateway modifying response headers.
- Error-handling middleware returning
text/htmlfor all errors.
Debugging Steps
- Check
Content-Typein the Network panel. - Compare response headers between working and failing endpoints.
- Inspect backend code/configuration for explicit
Content-Typesettings.
Solutions
- On the backend, consistently return
Content-Type: application/jsonand encode the body as UTF-8. Many frameworks also emitapplication/json; charset=utf-8; the important part is that the response body is actually valid JSON and uses a consistent UTF-8 encoding. - On the frontend, be cautious when parsing responses whose
Content-Typeis notapplication/json, or at least log them first.
Scenario 3: Trailing Commas / Single Quotes / Comments ("Fake JSON")
Symptoms
- You copy "JSON-like" content from logs, docs, or chat tools.
- Parsing it in code or tools fails with:
Unexpected token ','Unexpected token ':'Unexpected token '/'
Common Error Patterns
- Trailing commas
{ "name": "Alice", "age": 30, } - Single quotes
{ 'name': 'Alice' } - Comments in JSON
{ // user info "name": "Alice" }
Debugging Steps
- Paste the raw response/text into the JSON Editor.
- Let the tool auto-format and highlight error positions.
- Fix according to the hints: remove trailing commas, switch to double quotes, delete comments.
Solutions
- Always run "JSON from docs/logs" through a validator first.
- If you need "config with comments" in backend logs, use JSONC or YAML and clearly label it as "non-standard JSON".
Scenario 4: Backend Returns "Double-Serialized" JSON Strings
Symptoms
- The response body is a string that contains JSON as text, e.g.:
"{\"key\":\"value\"}" - The frontend calls
JSON.parseonce and gets a string, not an object; only a secondJSON.parseyields the object. - If your code assumes "one parse gives an object", it breaks.
Causes
- The backend calls
JSON.stringifyon data that is already a JSON string. - Or an extra layer of wrapping happens in logs/message queues.
Debugging Steps
- Inspect the raw response in the Network panel:
- Does it start and end with
"? - Does it contain many
\"inside?
- Does it start and end with
- In the console:
const once = JSON.parse(text); console.log(typeof once, once);- If
typeof once === 'string', it's double-serialized.
- If
Solutions
- On the backend, avoid calling
JSON.stringifyon data that is already a JSON string. - If you must support such an interface on the frontend, parse the outer layer first and explicitly verify the result is a string before parsing again. Do not blindly call
JSON.parsetwice on every response — fix the API contract whenever possible:Use this only when your API contract explicitly documents double encoding. Otherwise, treat it as a backend contract bug.export function parsePossiblyDoubleEncodedJson(text: string): unknown { const first = JSON.parse(text) if (typeof first !== 'string') { return first } return JSON.parse(first) }
Scenario 5: Large JSON Causing Timeouts / Memory Issues
A large payload is often valid JSON. The failure is usually a performance, memory, or transport problem — not a JSON syntax error.
Symptoms
- The API returns a very large JSON (several MB or more).
- When the frontend calls
JSON.parse:- The page freezes or even crashes;
- Or you get
Out of memory/Invalid argumenterrors in some environments.
Causes
- Parsing huge JSON in one go puts heavy pressure on the main thread and memory.
- Some environments (old browsers, low-end devices) have limits on single
JSON.parsecalls.
Debugging Steps
- Check the response size in the Network panel (
Size/Transferred). - Try opening the JSON file locally in an editor to see if it's similarly slow.
Solutions
- On the backend:
- Use pagination or cursor-based pagination for large lists;
- Return only necessary fields to reduce payload size.
- On the frontend:
- Use lazy loading / virtual lists for large datasets;
- Where possible, use streaming parsing (e.g., JSON stream libraries in Node.js).
Scenario 6: Encoding Issues (Non-UTF-8, BOM)
Symptoms
- The response fails to parse in some environments with vague errors.
- Opening the text in an editor reveals a BOM (
EF BB BF) or non-UTF-8 encoding.
Causes
- Some backends/proxies output UTF-8 with BOM or other encodings.
- For JSON exchanged between systems, UTF-8 is the required interoperable encoding. Producers must not add a byte order mark (BOM); parsers may choose whether to ignore one, so BOM-prefixed JSON can fail in strict parsers.
Debugging Steps
- Save the response as a file and open it in an editor that shows encoding (e.g., VS Code, Notepad++).
- Check for a BOM or non-UTF-8 encoding.
Solutions
- Ensure the backend outputs JSON as UTF-8 without BOM.
- Configure gateways/proxies not to add BOM or change encoding.
- In browser Fetch scenarios, the decoding chain handles some BOM cases, but the real issue may be: the server outputting non-UTF-8, the file content entering JavaScript string as
U+FEFF, proxy/transcoding corruption, unescaped control characters in JSON strings, or incorrect text decoding. Don't attribute all "vague parse errors" to BOM.
Scenario 7: Truncated JSON (Network Interruption / Timeout)
Symptoms
- The response is cut off during transmission.
- Errors like:
SyntaxError: Unexpected end of JSON input
Causes
- Unstable network, timeouts, or proxy interruptions truncate the JSON.
Debugging Steps
- Check the request status in the Network panel:
- Does it show
(failed),timeout,aborted, etc.?
- Does it show
- Inspect whether the response content is clearly truncated (e.g., last character is not
}or]).
Solutions
- Add retry logic on the frontend, especially for mobile/unstable networks.
- Optimize timeout and retry settings on the backend/ops side.
Scenario 8: Extra Text Mixed In (Prefix/Suffix Garbage)
Symptoms
- The response has extra text before or after the JSON, e.g.:
or
Data: {"key":"value"}{"key":"value"}---END--- - Calling
JSON.parseon the entire string fails.
Causes
- Some legacy systems/debug logic append extra text to responses.
- Logs/proxies add prefixes/suffixes.
Debugging Steps
- Inspect the full response text in the Network panel.
- Confirm whether there are extra characters before/after the JSON.
Solutions
- Fix at the source if possible: ensure responses are pure JSON.
- Do not use a regex to extract arbitrary JSON from a mixed response in production. JSON is nested and strings can contain braces, so a simple regular expression cannot reliably identify the intended JSON value. Problems include: top-level arrays
[], braces inside string fields, multiple JSON fragments, greedy matching, and masking of protocol-layer bugs. - Reliable alternatives:
- Fix the API so the response body is always pure JSON.
- Design separate endpoints for different content types.
- If the protocol uses a known wrapper format (SSE, NDJSON, JSONP, specific log format), use the corresponding parser.
- For ad-hoc debugging, copy the raw content into the JSON Editor and manually identify the JSON boundaries.
- Log limited, sanitized response fragments in code — don't guess JSON boundaries.
Scenario 9: Backend Returns "Half JSON, Half Text" Mixed Content
Symptoms
- The first part of the response is JSON, the rest is plain text or HTML, e.g.:
{"success":true} <script>...</script> JSON.parsefails when it encounters the non-JSON part.
Causes
- Error-handling logic outputs HTML/scripts after writing JSON.
- Some frameworks append debug info on exceptions.
Debugging Steps
- Inspect the full response text to see if there's content after the JSON.
- Check backend logs for exception stacks being written to the response.
Solutions
- Ensure each response is either pure JSON or pure HTML, not mixed.
- For error responses, use a consistent JSON structure (e.g.,
errorfield) and avoid appending HTML.
Scenario 10: Unvalidated User Input or Third-Party Data Passed to JSON.parse
Symptoms
- Frontend/backend directly calls
JSON.parseon user input, third-party webhooks, or queue messages. - When the data is invalid, it throws exceptions and can break the entire request flow.
Causes
- Missing pre-validation: length, character set, structure, etc.
- Assuming "the other party will always send valid JSON".
Debugging Steps
- Review all
JSON.parsecall sites in your code:- Is the data source trusted?
- Is it wrapped in
try...catch?
- For failing samples, paste them into the JSON Editor to see specific errors.
Solutions
- For all external input:
- Set a realistic byte-size limit before parsing untrusted input (e.g., max 1MB).
- Decode input as UTF-8.
- Reject malformed encoding where your platform exposes decoding errors.
- Parse inside
try...catch. - Validate the parsed value against a schema or application rules.
- Avoid logging full untrusted payloads, especially if they may contain secrets.
- JSON allows Unicode strings — don't restrict to "printable ASCII" only, as that would reject valid international data like
"São Paulo"or"日本語".
Once text can be parsed successfully, syntax validation is only the first step. Use JSON Schema validation to check required fields, data types, and allowed values before accepting the data in your application.
Troubleshooting Checklist (Worth Bookmarking)
When you hit a "JSON parse failed" error, troubleshoot in this order:
- Check status code: is it 2xx?
- Check Content-Type: is it
application/json? - Inspect response content:
- Is it pure JSON, or HTML/text?
- Are there extra characters before/after?
- Check size: is it unusually large (several MB+)?
- Validate with a tool:
- Paste the response into the JSON Editor to automatically check syntax errors.
- Check encoding: is there a BOM or non-UTF-8 encoding?
- Check logs: does the backend log show exception stacks written to the response?
- Check code:
- Is
JSON.parsewrapped intry...catch? - Are you trying to parse non-2xx responses?
- Is
How to Prevent JSON Parse Failures?
- Standardize API Contracts
- Success response:
{ "success": true, "data": {...} } - Error response:
{ "success": false, "error": { "code": "...", "message": "..." } } - All responses are pure JSON, with no extra text.
- Success response:
- Unified Parsing Logic on the Frontend
- Encapsulate a
fetchJsonutility:- Check status code
- Check
Content-Type - Then call
JSON.parse
- Route all API calls through this function to reduce repeated mistakes.
- Encapsulate a
- Logging and Monitoring
- For failed parses, log:
- Status code
- Content-Type
- First 1KB of the response (sanitized)
- This makes it easier to tell whether it's a backend or network issue.
- For failed parses, log:
- Use Tools Effectively
- During development:
- Use the JSON Editor to quickly validate API responses.
- Format complex structures before reading them.
- For production issues:
- Paste problematic samples into the editor to quickly locate syntax errors.
- During development:
Summary
- "JSON parse failed" can have many causes: HTML error pages, format errors, encoding issues, truncated responses, double serialization, and more.
- A systematic troubleshooting flow (status code → Content-Type → response content → tool validation) can significantly reduce debugging time.
- In the long run, standardizing API contracts, encapsulating parsing logic, and using validation tools are key to minimizing these issues.
Next time you hit a JSON parse error, try pasting the response into the JSON Editor first to quickly confirm whether it's a syntax issue, then decide whether to fix it on the frontend or escalate to backend debugging.
What's Next?
- Once the text can be parsed, syntax validation is only the first layer. Learn how to use JSON Schema validation to check structure, required fields, and data types.
- For a foundational overview of JSON structure and syntax rules, see What Is JSON?.
- For API design patterns and response structure best practices, see JSON Best Practices.
Have a question or feedback? Contact us