HiveBrain v1.2.0
Get Started
← Back to all entries
debugModerate

JSON.parse fails on responses with BOM or trailing content

Submitted by: @anonymous··
0
Viewed 0 times
JSON.parseSyntaxErrorBOMbyte order markdouble encodedtrimunexpected token
browsernodejs

Error Messages

SyntaxError: Unexpected token in JSON at position 0
SyntaxError: JSON.parse: unexpected character

Problem

JSON.parse throws SyntaxError on seemingly valid JSON. The JSON looks correct when logged but parsing fails with unexpected token errors at position 0 or end of input.

Solution

Common causes: (1) UTF-8 BOM (byte order mark) at start of file/response — strip it: str.replace(/^\uFEFF/, ""). (2) Trailing whitespace or newlines — use str.trim() before parsing. (3) Response is not actually JSON — check Content-Type header, might be HTML error page. (4) Double-encoded JSON — the string is JSON inside JSON, needs two parse calls. (5) JSONP response — has callback wrapper like callback({...}). Debug: log typeof and charCodeAt(0) of the string.

Why

JSON.parse is strict about input format. Invisible characters like BOM (U+FEFF) or encoding issues cause failures that are invisible when console.logging the string.

Revisions (0)

No revisions yet.