How to Fix "Unexpected Token" and Other Invalid JSON Errors
Errors such as "Unexpected token } in JSON at position 42" or "Expected property name or '}'" almost always come from a small syntax slip. JSON is stricter than JavaScript object syntax, and it is easy to write something that looks fine but is not valid. These are the mistakes behind the vast majority of parse errors. 1. Trailing commas JSON does not allow a comma after the last item in an object…
This article explains how to resolve "Unexpected token" and similar invalid JSON errors that typically stem from small syntax mistakes. JSON has stricter syntax rules than JavaScript objects, so what looks fine in JavaScript may not be valid JSON. The most common error is trailing commas – JSON does not allow commas after the last item in an object or array.
For example, { a : 1 , b : 2 } is not valid JSON, whereas { a : 1 , b : 2 } is. Another frequent mistake is using single quotes instead of double quotes for strings and keys. In JSON, strings and keys must always be enclosed in double quotes, so { name : Ada } is valid, but { name : 'Ada' } is not. JSON also disallows unquoted keys, single-line comments, leading zeros, hex values, and newline/tab characters in strings.
Additionally, invisible issues like a byte-order mark at the start of a file or two objects back to back without a single enclosing object or array can cause parse errors. To quickly diagnose and fix these issues, copy the exact text being parsed and paste it into an online JSON validator, which will pinpoint the line and column of the first error.
The first character before the reported position usually reveals the mistake – a missing or extra comma, for instance. Fix the error one at a time and re-validate the JSON. If the error occurs at position 0, examine the raw response body and check the HTTP status code to ensure you're dealing with actual JSON and not an error page or HTML.
When working with API responses that may contain sensitive data, use a browser-based validator to avoid uploading private information to external servers.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.