Few runtime errors interrupt frontend and backend development as frequently as SyntaxError: Unexpected token ... is not valid JSON. You make an API request, expect clean structured data, and instead your browser console or Node.js process crashes inside JSON.parse() or response.json(). Even more confusing, Chrome, Firefox, Safari, and Node.js format the exact same error differently—sometimes saying "Unexpected end of JSON input", other times pointing to a mysterious < character at position 0.
Unlike relaxed JavaScript object literals or Python dictionaries, JSON follows a strict, unambiguous grammar defined by RFC 8259. There is no tolerance for trailing commas, single quotes, unescaped line breaks, or invisible file headers. In this comprehensive guide, we walk through every major cause of JSON parse failures, show you how to diagnose each one in seconds, and share defensive parsing patterns that prevent crashes in production.
If you have a broken payload in your clipboard right now, paste it directly into our Online JSON Formatter & Validator to isolate the exact line and column before reading further.
- 1. Why Error Messages Differ Across Browsers
- 2. Unexpected Token
<(HTML Returned Instead of JSON) - 3. Unexpected End of JSON Input (Empty or Truncated Bodies)
- 4. Trailing Commas in Configs and Payloads
- 5. Single Quotes, Unquoted Keys, and Python Booleans
- 6. Unescaped Quotes, Newlines, and Control Characters
- 7. Hidden UTF-8 Byte Order Mark (BOM)
- 8. Double-Encoded JSON Strings & Number Precision
- 9. Production-Safe Defensive Parsing Wrapper
1. Why Error Messages Differ Across Browsers and Runtimes
Each JavaScript engine uses its own parser wording when reporting malformed JSON. Recognizing the equivalent messages saves debugging time when switching between Chrome DevTools, Firefox, Safari, or a Node.js server log:
| Runtime / Engine | Typical Error Message | What It Means |
|---|---|---|
| Chrome / Node.js (V8) | Unexpected token '<', "<!DOCTYPE "... is not valid JSON | Parser received HTML or non-JSON text starting with <. |
| Firefox (SpiderMonkey) | JSON.parse: unexpected character at line 1 column 1 | Exact line and 1-based column where parsing aborted. |
| Safari (JavaScriptCore) | JSON Parse error: Unrecognized token '<' | Equivalent to V8's unexpected token error. |
Python (json.loads) | json.decoder.JSONDecodeError: Expecting value: line 1 column 1 | Empty string, HTML page, or invalid literal at start of payload. |
2. Unexpected Token < (Receiving HTML Instead of JSON)
The single most common cause of Unexpected token '<' has nothing to do with malformed JSON syntax. Your client code called response.json() unconditionally, assuming the server returned JSON, when the server actually sent back an HTML document.
Common reasons an endpoint returns HTML instead of JSON include:
- HTTP 404 or 500 Pages: A typo in the API route (
/api/v1/userinstead of/api/v1/users) or an upstream reverse proxy timeout (502 Bad Gateway / 504 Gateway Timeout from Nginx or Cloudflare) serves a default HTML error page. - Authentication Redirects: When a session cookie expires, an auth middleware redirects the request to
/login, returning the login form HTML with HTTP status200 OK. - Missing
AcceptHeader: Certain frameworks (Laravel, Django, Rails) perform content negotiation and render an HTML view unless the request explicitly sendsAccept: application/json. - SPA Fallback Catch-All: Single-page app hosts configured to rewrite unknown routes to
/return your React/Vue shell HTML whenever an API path misses its proxy rule.
How to fix it: Open your browser's Network tab, click the failing request, and inspect the Response and Headers panels. In code, always check response.ok and verify the Content-Type header before calling response.json():
async function fetchJsonSafe(url, options = {}) {
const response = await fetch(url, {
...options,
headers: {
"Accept": "application/json",
...(options.headers || {})
}
});
const contentType = response.headers.get("content-type") || "";
const rawBody = await response.text();
if (!response.ok) {
throw new Error(`HTTP ${response.status} ${response.statusText}: ${rawBody.slice(0, 200)}`);
}
if (!contentType.includes("application/json")) {
throw new Error(`Expected application/json but received "${contentType}". Preview: ${rawBody.slice(0, 120)}`);
}
return JSON.parse(rawBody);
}
3. Unexpected End of JSON Input (Empty or Truncated Payloads)
When V8 throws SyntaxError: Unexpected end of JSON input (or Firefox reports end of data when reading object), the parser reached the end of the string before seeing a complete JSON value. This usually happens in three situations:
- HTTP 204 No Content or Empty 200 Body: Many
DELETEandPUTendpoints return status204 No Contentwith an empty body. Callingresponse.json()on an empty string""immediately throws. Always checkif (response.status === 204 || rawBody.trim() === "") return null;. - Missing Closing Braces or Brackets: A manual edit or log truncation cut off the final
}or]. Logs stored in database columns with aVARCHAR(255)limit are notorious for slicing off the end of webhook JSON. - Corrupted
localStorageReads: CallingJSON.parse(localStorage.getItem("prefs"))when the key doesn't exist passesnull(which coerces to"null"), whereas an empty string""throws. Wrap storage reads intry/catch.
4. Trailing Commas in Objects and Arrays
Developers write trailing commas every day in JavaScript, TypeScript, Python, and Rust because trailing commas prevent one-line diffs from polluting version control. In addition, configuration files like VS Code's settings.json and TypeScript's tsconfig.json use JSONC (JSON with Comments and Trailing Commas), which actively accepts trailing commas.
However, standard JSON.parse() and backend REST parsers strictly forbid trailing commas. The parser expects another property key or array element after every comma and fails when it hits } or ] instead:
Invalid (Trailing Comma)
{
"service": "billing",
"retries": 3,
"tags": [
"prod",
"eu-west",
],
}
Valid RFC 8259 JSON
{
"service": "billing",
"retries": 3,
"tags": [
"prod",
"eu-west"
]
}
How to fix it: If you maintain JSON config files by hand, validate them in our JSON Validator before committing, or enforce strict JSON formatting in Prettier/ESLint.
5. Single Quotes, Unquoted Keys, and Python Literals
A frequent mistake when copying test payloads from terminal logs happens when someone prints a JavaScript object via util.inspect() or a Python dictionary via print(my_dict) and pastes the output into an API client like Postman or cURL. Neither util.inspect() nor Python's str(dict) outputs valid JSON.
- Single quotes: Python prints
{'status': 'ok'}. JSON mandates double quotes (") for both keys and strings. - Unquoted property names: JavaScript object literals allow
{ id: 10, active: true }. JSON requires{ "id": 10, "active": true }. - Capitalized booleans &
None: Python outputsTrue,False, andNone. JSON requires lowercasetrue,false, andnull. - Unsupported JavaScript values:
undefined,NaN,Infinity, and functions are not valid JSON types. In fact,JSON.stringify({ x: undefined, y: NaN })silently dropsxand turnsyintonull.
# Python: NEVER do print(data) to create JSON
import json
data = {"id": 10, "active": True, "notes": None}
print(json.dumps(data)) # Output: {"id": 10, "active": true, "notes": null}
6. Unescaped Quotes, Newlines, and Control Characters
RFC 8259 forbids unescaped control characters (ASCII codes 0x00 through 0x1F) inside JSON string values. That includes literal Enter/newline breaks, literal Tab characters, and unescaped double quotes. Whenever you build JSON dynamically using template literals or string concatenation instead of a real serializer, user input containing quotes or line breaks will instantly corrupt the payload.
// DANGEROUS anti-pattern: manual string interpolation
const badJson = `{"comment": "${userComment}"}`;
// If userComment is: Line 1\nLine 2 or contains ", the JSON breaks (or enables JSON injection!)
// SAFE pattern: always serialize native objects
const safeJson = JSON.stringify({ comment: userComment });
If you must manually fix a hand-written string inside an editor, replace literal newlines with \n, tabs with \t, backslashes with \\, and internal double quotes with \".
7. Hidden UTF-8 Byte Order Mark (BOM)
One of the sneakiest JSON bugs occurs when a file passes visual inspection completely—every quote, bracket, and comma is spotless—yet JSON.parse() throws Unexpected token at position 0. This almost always points to an invisible UTF-8 Byte Order Mark (U+FEFF, bytes EF BB BF) prepended to the start of the file by older Windows Notepad versions, PowerShell 5 Out-File -Encoding utf8, or Excel exports.
Because RFC 8259 states that network-transmitted JSON must not begin with a BOM, JavaScript's JSON.parse() rejects it. You can strip a leading BOM safely in one line before parsing:
function stripBomAndParse(text) {
const cleaned = text.charCodeAt(0) === 0xFEFF ? text.slice(1) : text;
return JSON.parse(cleaned);
}
In Python, reading a file with encoding="utf-8-sig" automatically strips any BOM before passing the contents to json.load().
8. Double-Encoded JSON Strings & Large Integer Precision
Two subtle runtime bugs do not necessarily throw a SyntaxError, yet still break application logic:
Double-Encoded JSON
When a backend stores JSON inside a text column and then serializes the row again with JSON.stringify(), the API returns a JSON string containing escaped JSON inside it, like "{\"userId\":42,\"plan\":\"pro\"}". Notice the outer quotes and backslashes. Calling JSON.parse() once succeeds—and returns a string instead of an object, causing data.userId to evaluate to undefined.
To check whether a payload is double-encoded, inspect typeof parsed === "string". The permanent fix is on the server: avoid stringifying data that is already serialized as JSON (for example, use native PostgreSQL JSONB columns or parse stored text before wrapping it in an API response).
64-Bit Integer Precision Loss (JavaScript)
While valid in JSON syntax, numbers larger than Number.MAX_SAFE_INTEGER (9007199254740991, or 253 - 1)—such as Snowflake IDs or 64-bit database primary keys—silently lose their least significant digits when parsed into standard IEEE 754 JavaScript numbers. For example, 1234567890123456789 silently rounds to 1234567890123456800! APIs serving 64-bit IDs should always serialize them as strings ("id": "1234567890123456789").
9. Production-Safe Debugging & Validation Workflow
When debugging a stubborn JSON failure across microservices or third-party webhooks, follow this four-step diagnostic routine:
- Capture the raw response text before parsing: Log the HTTP status code,
Content-Typeheader, and the first 300 characters of the raw body. - Verify with cURL in the terminal: Run
curl -i -H "Accept: application/json" https://your-api.example/endpointto rule out browser-only CORS or cookie redirect issues. - Validate & Format Locally: Paste the raw body into the TechCar DevTools JSON Formatter. If there is a syntax error, it highlights the approximate line and column immediately without uploading sensitive staging payloads.
- Compare Working vs. Broken Payloads: If one environment works and another fails, paste both payloads into our JSON Diff Checker and click Format & Sort JSON First to isolate missing keys or type mismatches.
10. Quick CLI Validation Commands (cURL, jq & Python)
When working directly inside a terminal or CI/CD pipeline, you can validate JSON configuration files before deploying without opening a browser:
# 1. Validate a file using Python's built-in json module (no extra packages needed)
python3 -m json.tool config.json > /dev/null
# 2. Pretty-print and inspect an API response using jq
curl -sS -H "Accept: application/json" https://api.techcar.online/health | jq .
# 3. Validate JSON syntax in Node.js one-liner
node -e "JSON.parse(require('fs').readFileSync('config.json', 'utf8')); console.log('Valid JSON')"
Adding a pre-commit hook or CI check that validates every .json file in your repository catches accidental trailing commas and unescaped quotes before they ever break a production deployment.
If your team works across multiple languages, keep in mind that strictness differs slightly across standard libraries: Python's json.loads() permits NaN and Infinity by default unless you pass parse_constant, whereas Go's encoding/json maps JSON keys to exported struct fields case-insensitively unless you specify explicit `json:"field_name"` tags. Standardizing on strict RFC 8259 output across every service guarantees consistent parsing across browsers, Node.js, Python, and Go.
Frequently Asked Questions
Why does JSON.parse() allow numbers like -0 or scientific notation?
RFC 8259 officially supports negative signs, decimals, and scientific exponents like 1.5e10. However, leading zeros (such as 042), hexadecimal literals (0xFF), NaN, and Infinity are strictly invalid.
Can I add comments inside a package.json or API JSON body?
No. Standard JSON does not support // or /* */ comments. Only specialized editor formats like JSONC or JSON5 support comments; if you send comments to a REST API or npm, parsing will fail.
How do I fix "SyntaxError: JSON.parse: bad escaped character"?
This usually occurs when a Windows file path like "C:\Users\name" is placed unescaped inside JSON. The parser reads \U as an invalid escape sequence. Escape backslashes as "C:\\Users\\name" or use forward slashes.
What is the quickest way to validate a large JSON file safely?
You can upload local .json files directly into our JSON Formatter & Validator, which parses files locally in browser memory, or run python3 -m json.tool file.json > /dev/null from your terminal.