To fix Uncaught SyntaxError: Unexpected token ... in JSON when calling JSON.parse(), wrap the call in a try...catch block so malformed strings fail gracefully instead of crashing execution, and inspect or sanitize the raw input before parsing—most commonly when receiving plain text/HTML error pages instead of JSON, unquoted keys/single quotes, trailing commas, or a UTF-8 BOM (\uFEFF). Because JSON.parse() strictly requires standard RFC 8259 JSON (double quotes around keys and strings, no trailing commas, no comments, and no undefined), catching errors and validating the response or input resolves both crashes and bad payloads.
1. Wrapping JSON.parse() in a Guarded try...catch Helper
Always guard JSON.parse() with input validation and try...catch so invalid or non-string payloads return a safe fallback or structured error instead of throwing an uncaught SyntaxError:
// Safely parse a JSON string without throwing on malformed input
function safeJsonParse(rawInput, fallback = null) {
if (typeof rawInput !== "string") {
return fallback;
}
// Strip leading UTF-8 BOM if present, as some servers/files prepend \uFEFF
const cleaned = rawInput.replace(/^\uFEFF/, "").trim();
if (cleaned.length === 0) {
return fallback;
}
try {
return JSON.parse(cleaned);
} catch {
return fallback;
}
}
// Example usage:
console.log(safeJsonParse('{"role":"editor"}', {})); // { role: "editor" }
console.log(safeJsonParse("Not valid JSON <html/>", null)); // null
console.log(safeJsonParse("\uFEFF{\"ok\":true}", null)); // { ok: true }
- Prevents uncaught
SyntaxError: A single bad payload will not halt event handlers, loops, or request pipelines. - Handles empty strings and BOM: Empty responses or UTF-8 byte-order marks (
\uFEFF) frequently triggerUnexpected tokenerrors if passed raw.
2. Common Causes in fetch() / API Responses and Non-JSON Strings
In web apps, Unexpected token '<' in JSON or Unexpected token 'u' in JSON often happens when an API returns an HTML error page, plain-text message, or undefined string, or when source text uses non-JSON syntax like single quotes or trailing commas:
// Fetch and parse JSON safely while checking HTTP status and content
async function fetchJsonSafely(url, options = {}) {
if (typeof url !== "string" || url.trim().length === 0) {
throw new TypeError("Expected url to be a non-empty string.");
}
const response = await fetch(url, options);
const rawText = await response.text();
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${rawText.slice(0, 120)}`);
}
const trimmed = rawText.replace(/^\uFEFF/, "").trim();
if (trimmed.length === 0) {
return null;
}
try {
return JSON.parse(trimmed);
} catch (err) {
throw new Error(`Invalid JSON body: ${err.message}`);
}
}
// Example usage:
console.log(typeof fetchJsonSafely); // "function"
- Check
response.okand read.text()first: Reading.text()beforeJSON.parse()lets you inspect HTML/error text on404/500responses instead of getting a cryptic JSON syntax error. - Watch out for JS object literals vs. JSON:
{ name: 'Ali', }or'hello'is valid JavaScript syntax, not valid JSON—fix the producer/serializer to emit standard double-quoted JSON without trailing commas.
3. Debugging and Validating Malformed Payloads Before Parsing
When troubleshooting an unexpected token, log the exact raw string and character position (or slice around the failure) rather than guessing—especially when dealing with escaped quotes, newlines, or truncated strings:
// Parse JSON and include diagnostic context on failure for debugging
function parseJsonWithDiagnostics(rawText) {
if (typeof rawText !== "string") {
return { ok: false, data: null, error: "Input is not a string." };
}
const normalized = rawText.replace(/^\uFEFF/, "");
try {
const data = JSON.parse(normalized);
return { ok: true, data, error: null };
} catch (err) {
return {
ok: false,
data: null,
error: err.message,
preview: normalized.slice(0, 160)
};
}
}
// Example usage:
console.log(parseJsonWithDiagnostics("{bad: 'json'}"));
// { ok: false, data: null, error: "...", preview: "{bad: 'json'}" }
- Avoid
"undefined"orundefined: CallingJSON.stringify(undefined)returnsundefined(not a string), and parsing"undefined"throws aSyntaxError. - Fix the source whenever possible: Stripping or patching bad strings on the client is a safety net; ensure APIs set
Content-Type: application/jsonand serialize valid JSON properly.
TL;DR: Guard JSON.parse() with try...catch, strip any leading BOM (\uFEFF) or empty text, check response.ok and read .text() before parsing HTTP responses, and ensure the data uses strict JSON syntax (double quotes, no trailing commas or comments).