"Unexpected Token in JSON at Position 0" — What It Actually Means

By · Published

SyntaxError: Unexpected token X in JSON at position 0 is JSON.parse telling you the very first character it read wasn't valid JSON. Position 0 is the useful detail. The problem is the first character, which rules out a typo buried three levels deep in a large payload and narrows the cause down a lot.

The usual cause: you didn't get JSON back

The most frequent version is Unexpected token < in JSON at position 0. The < is the start of <!DOCTYPE html> or <html>, which means your code called JSON.parse on an HTML page. With API calls this happens all the time. The request hit a 404 page or a 500 error page, or got redirected to an HTML login page, and the calling code parsed the body as JSON without checking the status code or content type first.

const res = await fetch('/api/data')
const data = await res.json()   // throws here if the server actually sent back an HTML error page

// check first:
const res = await fetch('/api/data')
if (!res.ok) throw new Error(`Request failed: ${res.status}`)
const data = await res.json()
Advertisement

The other common one: parsing something that isn't a string

In Unexpected token u in JSON at position 0, the u is the start of the word undefined. A variable holding undefined got coerced to the string "undefined" before it reached JSON.parse. Usually a value that was supposed to be set (a cached response, a localStorage read that returned null) wasn't.

Finding the bad input

Log the raw response text before you parse it. Once JSON.parse has thrown, the original string is gone from that stack frame. Then paste exactly what you logged into a JSON formatter, not what you assumed the response looked like. The formatter converts the character offset into a line number, which matters more once the bad character is somewhere deep in a large payload instead of at position 0.

Advertisement

Try the JSON Formatter →

Related tools & guides

Part of JSON Tools: Format, Validate, Diff, Convert, and Generate Types