debugModerate
JSON.parse fails on responses with BOM or trailing content
Viewed 0 times
JSON.parseSyntaxErrorBOMbyte order markdouble encodedtrimunexpected token
browsernodejs
Error Messages
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.