Unexpected token in JSON at position N
JSON.parse hit a character it cannot accept. The position it gives you is where it stopped, not where you went wrong. The real mistake is usually a few characters earlier, so look just before that spot for a stray comma, the wrong kind of quote, or a missing brace.
How the message appears
The same fault, worded by different engines. V8 (Chrome, Node, Edge) changed its format around Chrome 109, so older and newer runtimes disagree about the same document.
The fix
Delete the comma after the last array item, and the comma after the last object key. A comma goes between two values, never after the last one.
{
"name": "Ada",
"roles": ["admin", "editor",],
}{
"name": "Ada",
"roles": ["admin", "editor"]
}The example travels in the URL fragment, which browsers never send to a server.
What causes it
You parsed something that was never JSON
You will usually see this as Unexpected token o in JSON at position 1, and you can read the answer straight out of it. Position 0 is [, position 1 is o, so the text being parsed is [object Object]. Something turned an object into a string with String(value) before JSON.parse ever saw it. The other common one is Unexpected token <. That means you parsed an HTML page, and it is almost always a 404 or 500 page arriving where you expected JSON.
A stray or missing comma
Either a comma after the last item, or no comma between two items. JavaScript lets you leave a comma after the last one. JSON does not. That is why code copied out of an editor so often breaks right here.
The wrong kind of quote
Single quotes, backticks, or the curly quotes that Word, Slack and Notion insert for you (‘ ’ “ ”). They look almost identical on screen. JSON strings take plain double quotes and nothing else.
Double-encoded JSON
The document holds a JSON string where you wanted a JSON object, so you have "{\"a\":1}" instead of {"a":1}. Parsing that once hands you back a string, not an object. Something ran JSON.stringify twice on the way in.
Worth knowing
- The position counts characters from the start of the string, not lines. Paste the document into the validator and it turns that number into a line and column you can actually find.
- If the position is 0 and the document looks perfect, you probably have a byte order mark. See the BOM page.
Written by Vishnu Shankar.