JSON Parse Error Debugging: Unexpected Token, Trailing Commas, Quotes, and Large Numbers

JSON.parse() is strict. That is good for data exchange, but it also means small differences between JavaScript object literals, JSON-like logs, and valid JSON can break an API or configuration file.

Most JSON parse errors come from one of these sources:

  • trailing commas
  • single quotes
  • unquoted keys
  • comments
  • copied log prefixes
  • invalid escape sequences
  • a response that is HTML or plain text, not JSON
  • large numbers losing precision after parsing

This guide gives you a practical debugging workflow.

JSON is not a JavaScript object literal

This is valid JavaScript, but invalid JSON:

{
  name: 'Ada',
  active: true,
}

Valid JSON must use double-quoted keys and strings, and it cannot have a trailing comma:

{
  "name": "Ada",
  "active": true
}

If a browser console, documentation page, or backend log shows "JSON" with single quotes or unquoted keys, treat it as JSON-like text until it passes a strict parser.

Common Unexpected token causes

Unexpected token means the parser found a character that is not allowed at that position.

Examples:

{"name": "Ada",}

Trailing comma after "Ada" is invalid JSON.

{'name': 'Ada'}

Single quotes are invalid JSON.

{name: "Ada"}

Object keys must be double quoted.

{
  "name": "Ada" // user name
}

Comments are invalid JSON.

Check whether the response is really JSON

When an API call fails with a JSON parse error, inspect the raw response before changing the parser.

Common surprises:

  • the server returned an HTML error page
  • a proxy returned a login page
  • an endpoint returned an empty body with 204 No Content
  • a backend printed a warning before the JSON
  • the response is compressed or encoded unexpectedly

In frontend code, log the response as text once:

const text = await response.text()
console.log(text)
const data = JSON.parse(text)

If the first character is <, you are probably parsing HTML. If it starts with Warning: or a stack trace, fix the server output before parsing.

API response debugging workflow

For production API bugs, do not start by editing the JSON parser. First separate transport problems from syntax problems:

  1. Check the HTTP status code.
  2. Check the Content-Type header.
  3. Read the body as text once.
  4. Save the raw body before any formatting or decoding.
  5. Validate the raw body as strict JSON.

Example:

const response = await fetch('/api/orders')
const contentType = response.headers.get('content-type') || ''
const text = await response.text()

if (!contentType.includes('application/json')) {
  throw new Error(`Expected JSON, got ${contentType}: ${text.slice(0, 120)}`)
}

const data = JSON.parse(text)

This makes the real issue visible. A 401 login page, a CDN error page, or a backend warning printed before the JSON can all produce the same Unexpected token error in application code.

Logs and copied snippets are often not JSON

Backend logs, browser console output, and documentation examples often show JSON-like objects rather than strict JSON.

Common examples:

INFO response: {"ok":true}
{ id: 123, status: 'paid' }
payload={"name":"Ada"}

Before pasting a snippet into a parser, remove log prefixes, timestamps, shell prompts, and variable names. Then check whether keys and strings are double quoted.

If a log contains escaped JSON inside another string, you may need to decode one layer first:

{
  "message": "{\"event\":\"login\",\"ok\":true}"
}

In that case, message is a JSON string that contains another JSON document. Parse the outer object first, then parse message only if your application expects nested JSON.

Validate before formatting

A formatter makes valid JSON easier to read. It cannot safely format invalid JSON without making assumptions.

Use a JSON formatter to locate:

  • the first invalid character
  • the line and column of the error
  • mismatched braces or brackets
  • invalid string escapes
  • missing commas between properties

Then fix the source data. Do not rely on a formatter to "repair" production payloads unless you understand exactly what it changed.

Escape characters correctly

Inside JSON strings, backslashes are escape characters.

Valid:

{
  "path": "C:\\\\Users\\\\Ada",
  "quote": "She said \\\"hello\\\""
}

Invalid:

{
  "path": "C:\Users\Ada"
}

If data comes from a programming language string literal, remember there may be two escaping layers: the language string and the JSON string.

JSON from AI tools and relaxed config files

JSON returned by AI tools, copied from README files, or taken from configuration files is often close to JSON but not valid strict JSON. Watch for:

  • Markdown fences such as ````json`.
  • Comments copied from config files.
  • Trailing commas after the last item.
  • Smart quotes copied from rich text.
  • Explanatory text before or after the object.
  • undefined, NaN, or Infinity, which are not valid JSON values.

If you need machine-readable output, ask the upstream system to return only strict JSON and validate it before using it. For human-maintained config, JSON5 or JSONC may be fine, but convert it to strict JSON before sending it to an API or storing it in a strict JSON database column.

Large numbers can lose precision

JSON supports numbers, but JavaScript parses them into the Number type. Very large integers can lose precision.

Risky:

{
  "order_id": 12345678901234567890
}

Safer:

{
  "order_id": "12345678901234567890"
}

IDs, payment references, and database primary keys that exceed JavaScript's safe integer range should usually be serialized as strings.

Common fixes by error text

Different engines phrase JSON errors differently, but these patterns are useful:

Error clueLikely causeWhat to check
Unexpected token <HTML responseAuth redirect, proxy error, 404/500 page
Unexpected token /CommentJSONC/JSON5 copied into strict JSON
Unexpected token }Trailing comma or missing valueLast property in an object
Unexpected token uundefinedMissing variable serialized as text
Unexpected end of JSON inputEmpty or truncated body204 No Content, network abort, partial file
Bad control characterRaw newline in stringEscape line breaks as \\n

This table is a starting point, not a replacement for checking the raw payload. Always validate the exact text that your parser receives.

Debugging checklist

When JSON parsing fails:

  1. Copy the raw response or file content.
  2. Confirm it starts with {, [, ", a number, true, false, or null.
  3. Check for HTML, log prefixes, warnings, or empty responses.
  4. Remove trailing commas and comments.
  5. Replace single quotes with double quotes only if they are actually JSON strings.
  6. Verify escaping inside strings.
  7. Treat very large IDs as strings.

Use the JSON Formatter to validate and format the payload. If the JSON contains encoded URL fields, use the URL Encoder/Decoder. If the JSON contains Base64 fields, decode them separately with the Base64 Tool before assuming the whole API response is broken.