Have you ever sat up late, staring at a red error message that simply reads "Unexpected token"? JSON (JavaScript Object Notation) is the lingua franca for data exchange, but even a stray comma or the wrong type of quotes can break everything. If you want a quick sanity check, run your payload through a JSON formatter before you start debugging.
In this guide, I'll unpack the most frequent JSON errors I've seen over the years, show you exactly how to identify them, and offer practical fixes you can apply right away. Whether you're just getting started with APIs or you've been integrating services for years, knowing how to read and correct these errors will save you a lot of frustration.
Let's walk through the biggest offenders one by one, with simple examples and some tips for keeping your data tidy.
Trailing Commas: The Hidden Culprit
One of the most common JSON mistakes is leaving a comma after the last item in an object or array. Unlike JavaScript, JSON doesn't tolerate trailing commas. This is why parsers throw errors like "Unexpected token '}'" when the only thing wrong is an extra comma.
Invalid JSON (notice the comma after the last property):
{
"name": "John Doe",
"age": 30,
"city": "New York",
}
When you try to parse this, you'll get a syntax error. To fix it, simply remove the final comma:
{
"name": "John Doe",
"age": 30,
"city": "New York"
}
How to avoid it
- Use a JSON validator or linter integrated into your editor; many will highlight trailing commas automatically.
- Configure your formatter (Prettier, ESLint, etc.) to remove trailing commas when saving.
- When copying objects from JavaScript, run them through a validator such as CodeItBro's JSON validator before using them in configuration files or API calls.
Single Quotes Instead of Double Quotes
JSON is strict about quotes: all strings and property names must use double quotes. JavaScript allows single quotes, but JSON doesn't, so copying code from JS can lead to unexpected parser errors.
Invalid JSON using single quotes:
{
'name': 'John Doe',
'active': true
}
The parser reads the single quote as an unexpected character and stops. The fix is straightforward: replace all single quotes with double quotes:
{
"name": "John Doe",
"active": true
}
Why this matters
Using consistent double quotes ensures your JSON is valid across languages and platforms. It avoids subtle bugs when different parsers interpret single quotes differently.
Unquoted Property Names
In JavaScript object literals, property names can sometimes omit quotes. In JSON, that is never allowed. All keys must be enclosed in double quotes.
Invalid JSON without quoted keys:
{
name: "John Doe",
age: 30
}
This will throw an error like Unexpected token 'n' because the parser expects a quoted string. Correct it by wrapping property names in double quotes:
{
"name": "John Doe",
"age": 30
}
Modern editors usually highlight unquoted keys for you. Turning on JSON syntax mode will catch these mistakes early.
Missing Commas Between Elements
Another common gotcha is forgetting to separate properties or array items with commas. JSON uses commas between every pair of elements except the last one.
Invalid JSON missing a comma:
{
"firstName": "John"
"lastName": "Doe"
}
This input produces an error such as "Unexpected string". To correct it, add the missing comma:
{
"firstName": "John",
"lastName": "Doe"
}
When your error points to a seemingly valid line, check the previous line for a missing comma; that pattern reveals this error quickly.
Mismatched Brackets and Braces
Every opening { must have a closing }, and every [ must have a matching ]. It sounds obvious, but in long or deeply nested JSON, mismatched brackets are easy to overlook. Parsers typically complain with messages like "Unexpected end of JSON input".
Invalid JSON missing a closing brace:
{
"users": \[
{"name": "Alice"},
{"name": "Bob"}
\],
"total": 2
To fix this, ensure every array and object is properly closed:
{
"users": \[
{"name": "Alice"},
{"name": "Bob"}
\],
"total": 2
}
Most modern editors highlight matching brackets. You can also use a JSON formatter to indent nested levels, making mismatches obvious.
Invalid Number Formats
JSON supports numbers but only in standard decimal form. Leading zeros, hexadecimal notation and special values like NaN or Infinity are not valid.
Invalid JSON with bad number formats:
{
"quantity": 007,
"price": 0xFF,
"discount": NaN
}
To correct this, remove leading zeros, convert hex to decimal, and replace non‑numbers with null:
{
"quantity": 7,
"price": 255,
"discount": null
}
Using consistent number formats avoids silent conversions and parser errors. For example, 1.5e10 (scientific notation) is perfectly valid.
Unsupported Data Types
JSON is limited to six data types: string, number, boolean, null, array and object. JavaScript features such as undefined, functions, dates, regular expressions and comments are not valid JSON, and including them will cause parsers to choke.
Invalid JSON with unsupported types:
{
"name": "John",
"age": undefined,
"callback": function() { return true; },
"created": new Date()
}
Valid JSON uses only compatible values:
{
"name": "John",
"age": null,
"callback": null,
"created": "2025-01-30T10:30:00Z"
}
When converting from JavaScript:
- Replace undefined with null.
- Convert functions to strings or remove them entirely.
- Represent dates as ISO 8601 strings.
- Turn regular expressions into plain strings.
- Use toJSON() on custom objects to serialize them.
Comments in JSON
Because JSON is meant to be a pure data format, comments are not permitted. In configuration files where you want to explain values, comments can be tempting, but parsers will reject them.
Invalid JSON with comments:
{
// User information
"name": "John Doe",
/* Age in years */
"age": 30
}
To include notes, you have a few options:
- Add a dedicated _comment field in your object. Since it's a string, parsers will accept it.
- Keep separate documentation in your project (README, docs folder, etc.).
- Use JSONC (JSON with comments) only when your tooling explicitly supports it.
Invalid Escape Sequences
Strings in JSON can include escape sequences, but only a specific set is allowed (e.g., \\n for newline, \\t for tab, unicode escapes like \\u00A9). Unrecognized escapes will cause errors.
Invalid JSON with bad escape sequences:
{
"path": "C:\\\\new\\\\folder",
"message": "Line 1\\\\xLine 2"
}
Valid JSON uses correct escapes:
{
"path": "C\\\\\\\\new\\\\\\\\folder",
"message": "Line 1\\\\nLine 2"
}
Keep a list of valid escape sequences handy, or rely on your editor to highlight invalid ones.
Duplicate Keys
While some parsers allow duplicate property names, the JSON specification does not define how duplicates should be handled. Including the same key twice can produce unpredictable results. For example, JavaScript tends to keep the last value, but other languages may use the first or throw an error.
Problematic JSON with duplicate keys:
{
"name": "John Doe",
"age": 30,
"name": "Jane Doe"
}
Always ensure each key appears only once:
{
"firstName": "John",
"lastName": "Doe",
"age": 30
}
Using meaningful, unique property names makes your data predictable across platforms.
Debugging Strategies & Best Practices
When you're dealing with a large JSON file and the error isn't obvious, systematic debugging helps pinpoint the issue.
Try these techniques:
- Use a JSON validator. Online tools highlight errors and show line numbers. Plug in your JSON and fix the highlighted section.
- Format the file first. Proper indentation reveals structural issues like mismatched brackets.
- Binary search your JSON. Comment out (or remove) half the content, validate the remaining half, and repeat until you isolate the problem.
- Check the encoding. Ensure your file is UTF‑8; hidden byte order marks or special characters can cause cryptic errors.
- Validate programmatically. Wrap your parsing in a try/catch block and log the error message and position.
Prevent errors before they happen by following these best practices:
- Schema validation. Define a JSON schema and validate data against it.
- Automate formatting. Configure your editor to auto-format JSON on save.
- Use linting. Integrate a linter (ESLint with JSON plugins) to catch issues as you type.
- Review JSON in code reviews. Treat configuration changes as code and review them carefully.
- Version control. Track your JSON files in git or another VCS so you can identify when problems were introduced.
- Generate JSON programmatically. Use libraries or serialization functions; they won't forget commas or misquote strings.
- Test thoroughly. Include JSON validation in your automated tests.
Conclusion
Getting JSON right isn't glamorous, but it's essential. A tiny typo can cascade into hours of debugging if you're not careful. By understanding the rules-no trailing commas, double‑quoted strings and keys, proper numbers, valid escape sequences, and no duplicates-you can eliminate most syntax errors before they reach production. When issues do crop up, systematic debugging and good tooling will help you find and fix them quickly.
Have you battled any of these errors recently? Which tools or techniques saved your day? Share your stories in the comments and let's help each other avoid late-night JSON headaches. And if you've found this guide helpful, don't forget to bookmark it or share it with your team. Happy coding!
Top comments (0)