DeveloperJune 29, 2025·9 min read

JSON Parse Error: How to Fix "Unexpected Token" and Other JSON Errors

Getting a JSON parse error in your console? This guide covers every common cause — trailing commas, single quotes, unquoted keys, missing commas, and comments — with before/after examples and the fastest way to find the exact error line.

JSON parse error: Unexpected token is the error message that appears when your code calls JSON.parse() on text that is not valid JSON. The frustrating part is that the text often looks correct — because it is valid JavaScript, and JavaScript is far more lenient than JSON. This guide covers every common cause with before-and-after examples, a regex fix where applicable, and the fastest way to find the exact line causing the error.

Why JavaScript objects break JSON.parse()

JSON was designed to be a strict, language-independent data format. JavaScript object literals were designed for convenience. The result is that several things that are perfectly valid in a JavaScript object are outright illegal in JSON — and JSON.parse() has zero tolerance for any of them.

JavaScript object literal vs valid JSON — syntax differencesSide-by-side comparison showing a JavaScript object on the left with features that are invalid in JSON: single quotes, unquoted keys, trailing comma, and a comment. The right panel shows the corrected valid JSON with double quotes on all strings and keys, no trailing comma, and no comment.JavaScript object (valid JS, breaks JSON)Valid JSON (what JSON.parse() expects)vs1234567891011{ name: 'Alice'❌ single quotes age: 30, active: true,❌ trailing comma // comment❌ no comments in JSON score: 9.5, tags: [ 'dev',❌ single quotes 'seo' ]}12345678910{ "name": "Alice",✅ double quotes "age": 30, "active": true, "score": 9.5,✅ no comment needed "tags": [ "dev",✅ double quotes "seo"✅ no trailing comma ]}JSON.parse() runs on the right ✅ — paste broken JSON into the formatter to highlight the exact line causing the error
JavaScript object literals allow single quotes, trailing commas, and comments — JSON does not. These differences cause every "Unexpected token" parse error.

The diagram above shows the four most common differences between JavaScript and JSON. Every "Unexpected token" error is caused by one of these — or a combination of them. The rest of this post fixes each one individually.

Fix 1 — Trailing comma (the #1 cause)

JavaScript allows — and many style guides encourage — trailing commas after the last item in an object or array. JSON does not allow them under any circumstances. This is the most common source of "Unexpected token }" and "Unexpected token ]" errors.

// Breaks JSON.parse() ❌
{
  "name": "Alice",
  "age": 30,        ← trailing comma after last property
}

// Valid JSON ✅
{
  "name": "Alice",
  "age": 30
}

Real example: A developer copied a config object from a .js file into a .json config file. The JS file had trailing commas (enforced by ESLint). The JSON parser threw SyntaxError: Unexpected token } in JSON at position 42. The fix was removing the trailing comma on the last property.

Find all trailing commas with regex: In VS Code, open Find (Ctrl+F), enable regex mode, and search for:

,\s*([}\]])

Replace with: $1 — this removes the comma before any closing brace or bracket.

Fix 2 — Single quotes instead of double quotes

JSON requires double quotes for all strings — both keys and values. Single quotes produce an "Unexpected token '" error immediately.

// Breaks JSON.parse() ❌
{
  'name': 'Alice',
  'age': 30
}

// Valid JSON ✅
{
  "name": "Alice",
  "age": 30
}

Real example: An API was returning JSON generated by a Python script that used Python's str(dict) to serialise a dictionary instead of json.dumps(). Python's native dict representation uses single quotes. The frontend's JSON.parse(response) threw an immediate parse error. The fix was changing the backend to use json.dumps(data).

Quick fix for one-off text: If you have a string with single-quoted keys and you need to convert it quickly, our JSON Formatter & Validator will highlight the exact position of the first single quote so you can find and fix them systematically.

Fix 3 — Unquoted keys

JavaScript object shorthand lets you write {name: "Alice"} without quoting the key. JSON requires all keys to be double-quoted strings — always.

// Breaks JSON.parse() ❌
{
  name: "Alice",
  age: 30
}

// Valid JSON ✅
{
  "name": "Alice",
  "age": 30
}

Real example: A developer was hand-writing a JSON config for a Next.js project and wrote it like a JavaScript object (no quotes on keys). The config file reader threw JSON Parse error: Expected '"'. The fix: quote every key.

In VS Code: If you have a file full of unquoted keys, this regex Find & Replace converts them. Find: (\w+): — Replace: "$1":. Run carefully — this will also match things inside string values, so review each replacement.

Fix 4 — Missing comma between items

Forgetting a comma between two properties produces some of the most confusing error messages because the parser points to the second property, not the missing comma before it.

// Breaks JSON.parse() ❌ — error points to "age" not to the missing comma
{
  "name": "Alice"
  "age": 30
}
// SyntaxError: Unexpected string in JSON at position 20

// Valid JSON ✅
{
  "name": "Alice",
  "age": 30
}

Real example: An automated script was building a JSON payload by string concatenation and forgot to add a comma between dynamically generated properties. The error message said "Unexpected string" and pointed to the second property name — which confused everyone looking for the bug because the string itself was correct. The missing comma before it was the actual problem.

Fix 5 — Comments in JSON

JavaScript supports // single-line and /* */ block comments. JSON supports neither. A comment anywhere in a JSON string causes an immediate parse error.

// Breaks JSON.parse() ❌
{
  "timeout": 30,   // seconds
  "retries": 3
}

// Valid JSON ✅ — remove the comment
{
  "timeout": 30,
  "retries": 3
}

Real example: A team was maintaining a config.json file with inline comments explaining each setting. It worked fine in a code editor that supported JSONC (JSON with Comments), but broke when the file was read by a Node.js script using JSON.parse(fs.readFileSync('config.json', 'utf8')). The fix was switching to config.jsonc and using a JSONC-compatible parser, or removing the comments from the JSON file entirely.

If you need comments in JSON config files, consider JSONC (supported by VS Code and TypeScript) or JSON5. Both are supersets of JSON that allow comments. Standard JSON.parse() will reject both — you need a compatible parser.

How to find the exact line causing the JSON error

The error message tells you a character position, not a line number, which is unhelpful in a large JSON blob. Here are three ways to find the exact location:

Method 1 — JSON Formatter tool (fastest): Paste your broken JSON into our JSON Formatter & Validator. It highlights the error with the exact line number and a description of what is wrong. For most errors this is the fastest path — paste, see the red highlight, fix it.

Method 2 — Browser console: Open DevTools (F12) → Console → type:

try {
  JSON.parse(`YOUR_JSON_HERE`);
} catch (e) {
  console.log(e.message); // shows position
}

The error message includes the character position. Count to that position in your JSON (or use Ctrl+G in VS Code to jump to a specific character position).

Method 3 — VS Code: Rename the file to .json extension. VS Code's built-in JSON validator underlines syntax errors in real time and shows the problem on hover — no extensions required.

Error messageMost likely causeFix
Unexpected token }Trailing comma before a closing braceRemove the comma after the last property
Unexpected token ]Trailing comma in an arrayRemove the comma after the last array item
Unexpected token 'Single-quoted string or keyReplace all single quotes with double quotes
Expected '"'Unquoted keyWrap the key in double quotes
Unexpected stringMissing comma between propertiesAdd a comma at the end of the previous property
Unexpected token /Comment in JSONRemove the comment
Unexpected end of JSON inputTruncated or empty stringCheck the full JSON was received; log the raw string before parsing

How to validate JSON before parsing it in code

The most reliable way to prevent JSON parse errors in production is to validate before you parse. In Node.js:

function safeParseJSON(str) {
  try {
    return { data: JSON.parse(str), error: null };
  } catch (e) {
    return { data: null, error: e.message };
  }
}

const { data, error } = safeParseJSON(responseText);
if (error) {
  console.error('JSON parse failed:', error);
  console.error('Raw string:', responseText.slice(0, 200)); // log first 200 chars
}

Logging the raw string before the error is the most useful debugging technique — it reveals immediately if the API returned an HTML error page instead of JSON, if the string was truncated, or if it starts with a BOM character.

For interactive testing and fixing, paste your JSON into the JSON Formatter & Validator — it highlights every error with the line number and a plain-English description.

Key takeaways

  • JSON is stricter than JavaScript: no single quotes, no unquoted keys, no trailing commas, no comments.
  • The most common error is a trailing comma after the last item in an object or array — copied from JavaScript where it is valid.
  • The error message gives a character position, not a line number — paste into the JSON Formatter to find the exact line.
  • Wrap JSON.parse() in a try/catch and log the raw string on failure — it will tell you exactly what was received.
  • If you need comments or trailing commas in config files, use JSONC (.jsonc) or JSON5 with a compatible parser.

Official references and further reading

These three sources are the authoritative references for JSON syntax rules, the official standard, and the browser API — useful when you need to go deeper than a quick fix.

  • JSON.org — The Official JSON Specification — Douglas Crockford's original JSON specification. The railroad diagrams on this page show exactly which characters are valid at every position in a JSON document. If you are unsure whether something is legal JSON, this is the definitive answer.
  • RFC 8259 — The JSON Data Interchange Standard (IETF) — The formal IETF internet standard that every conforming JSON parser implements. Section 7 (Strings) and Section 9 (Numbers) are the most referenced sections when diagnosing parse errors with unusual character encoding or number formatting.
  • MDN Web Docs — JSON.parse() — Mozilla's complete reference for the JSON.parse() method, including the reviver parameter, every thrown exception type, and browser compatibility. The error table at the bottom maps exception messages to their underlying causes.

Frequently asked questions

What does "Unexpected token u in JSON at position 0" mean?

The first character of your string is u — which means the string is undefined. You are calling JSON.parse(undefined), which coerces undefined to the string "undefined" and immediately fails. Fix: check that the value you are parsing is actually a string before calling JSON.parse(). Add: if (typeof data !== 'string') return;

What does "Unexpected end of JSON input" mean?

The JSON string is cut off before it is complete — a missing closing brace, bracket, or quote at the end. Common causes: the API response was truncated due to a network error, a streaming response was not fully awaited, or a fetch call used response.text() without waiting for the full body. Log responseText.length and the last 50 characters to diagnose.

JSON.parse() works in the console but fails in production. Why?

The most common reason: the data source is different. In production, the API might return HTML (an error page or redirect) instead of JSON — and JSON.parse(<html>...) throws immediately. Check response.headers.get('content-type') before parsing — it should contain application/json. If it says text/html, the server sent an error page.

Is there a way to allow comments in JSON?

Yes — use JSONC (JSON with Comments, supported natively by VS Code and TypeScript's tsconfig.json) or JSON5 (a library available for Node.js and browsers). Both extend JSON to allow comments and trailing commas. Use them for config files; use standard JSON for API data interchange.

Can I fix JSON automatically without finding each error manually?

For common errors like trailing commas and single quotes, there are libraries that attempt to repair JSON: json-repair (npm) and Python's json-repair package both handle the most common mistakes automatically. For manual fixing, the JSON Formatter highlights each error with its line number so you can fix them one by one in under a minute for most real-world JSON blobs.

Free tool

Try the JSON Formatter & Validator

Use our free json formatter & validator to calculate results instantly — no signup required.

Open JSON Formatter & Validator
Tags:jsondebuggingjavascriptjson parsesyntax errorapi