How to Fix Common JSON Syntax Errors: A Debugging Guide
JSON looks simple, but it is surprisingly strict. A single misplaced comma, an unquoted key, or a trailing character can cause your entire payload to fail parsing. If you have ever stared at a SyntaxError: Unexpected token message trying to figure out what went wrong, this guide is for you. We will walk through the ten most common JSON syntax errors, show you exactly what is broken in each case, and give you the corrected version.
Why JSON Parsing Fails
JSON (JavaScript Object Notation) follows a strict specification defined in RFC 8259. Unlike JavaScript object literals, which are forgiving about formatting, JSON has no flexibility. Every string must use double quotes. Every key must be quoted. No trailing commas. No comments. No special values like undefined or NaN.
Most JSON errors come from hand-editing files, copying data from JavaScript source code, or receiving malformed responses from APIs. The parser reads your input character by character, and the moment it encounters something unexpected, it stops and throws an error. Understanding the spec is the key to fixing these errors quickly.
The 10 Most Common JSON Syntax Errors
1. Trailing Commas
This is the single most common JSON error. JavaScript and TypeScript allow trailing commas in arrays and objects, so developers habitually add them. JSON does not.
Wrong:
{
"name": "Alice",
"age": 30,
}Fixed:
{
"name": "Alice",
"age": 30
}Remove the comma after the last property or array element. This applies to both objects and arrays. The error message is usually Unexpected token } because the parser expects a value after the comma, not a closing brace.
2. Single Quotes Instead of Double Quotes
JSON requires double quotes for all strings and keys. Single quotes are valid in JavaScript and Python, but not in JSON.
Wrong:
{
'name': 'Alice',
'active': true
}Fixed:
{
"name": "Alice",
"active": true
}Replace every single quote with a double quote. If your string contains a literal double quote, escape it with a backslash: "She said \"hello\"".
3. Unquoted Keys
In JavaScript, object keys do not need quotes if they are valid identifiers. In JSON, every key must be a double-quoted string. No exceptions.
Wrong:
{
name: "Alice",
age: 30
}Fixed:
{
"name": "Alice",
"age": 30
}4. Missing Commas Between Items
When you add a new property to a JSON object or a new item to an array, it is easy to forget the comma separating it from the previous item.
Wrong:
{
"name": "Alice"
"age": 30
}Fixed:
{
"name": "Alice",
"age": 30
}The parser sees "age" right after "Alice" and expects either a comma or a closing brace. The error message typically says Unexpected string at the position of the second key.
5. Undefined, NaN, and Infinity Values
JavaScript has several special values that do not exist in JSON. When you serialize a JavaScript object that contains undefined, NaN, or Infinity, those values either get dropped or converted to null. But if someone hand-writes them into JSON, the parser rejects them.
Wrong:
{
"count": NaN,
"max": Infinity,
"callback": undefined
}Fixed:
{
"count": null,
"max": null
}Replace NaN and Infinity with null or a sensible default number. Remove properties with undefined values entirely, since JSON has no concept of undefined.
6. Comments in JSON
JSON does not support comments. This surprises many developers who are used to adding // or /* */ annotations in configuration files.
Wrong:
{
// Database connection settings
"host": "localhost",
"port": 5432, /* default PostgreSQL port */
"name": "mydb"
}Fixed:
{
"host": "localhost",
"port": 5432,
"name": "mydb"
}Remove all comments. If you need comments in config files, consider using JSONC (JSON with Comments), which is supported by VS Code and TypeScript config files, or switch to YAML.
7. Trailing Characters After JSON
Sometimes a JSON string has extra characters after the closing brace or bracket. This can happen when concatenating multiple JSON objects, when a server returns extra whitespace or debug output, or when copying from a terminal that appends a prompt.
Wrong:
{"name": "Alice"}{"name": "Bob"}Fixed (as an array):
[{"name": "Alice"}, {"name": "Bob"}]A valid JSON document must contain exactly one top-level value. If you have multiple JSON objects concatenated together (sometimes called NDJSON or JSON Lines), wrap them in an array or process each line separately.
8. Unescaped Special Characters in Strings
JSON strings cannot contain literal newlines, tabs, or backslashes. These characters must be escaped with a backslash prefix. This is a frequent issue when embedding file paths, regex patterns, or multi-line text.
Wrong:
{
"path": "C:\Users\alice\docs",
"message": "Line 1
Line 2"
}Fixed:
{
"path": "C:\\Users\\alice\\docs",
"message": "Line 1\nLine 2"
}Backslashes must be doubled (\\), literal newlines replaced with \n, and tabs replaced with \t. Other characters that need escaping include double quotes (\"), carriage return (\r), form feed (\f), and backspace (\b).
9. Missing Closing Braces or Brackets
In deeply nested JSON, it is easy to lose track of opening and closing braces or brackets. This is especially common when editing JSON by hand in a plain text editor without bracket matching.
Wrong:
{
"user": {
"name": "Alice",
"address": {
"city": "Berlin"
}
}Fixed:
{
"user": {
"name": "Alice",
"address": {
"city": "Berlin"
}
}
}The error typically appears as Unexpected end of JSON input, which means the parser reached the end of the string while still expecting more data. Count your opening and closing braces to make sure they match. A formatter tool will flag this instantly.
10. Duplicate Keys
The JSON spec says duplicate keys produce undefined behavior. Most parsers silently accept them and use the last value, but this can hide bugs and cause subtle issues when the behavior differs between parsers.
Problematic:
{
"name": "Alice",
"age": 30,
"name": "Bob"
}Fixed:
{
"name": "Bob",
"age": 30
}Decide which value is correct and remove the duplicate. Linting tools like jsonlint will warn about duplicate keys even though JSON.parse() silently accepts them.
How to Read JSON Error Messages
JSON parsers in different languages report errors differently, but they all give you the same essential information: what went wrong and where.
JavaScript (JSON.parse)
In browsers and Node.js, JSON.parse() throws a SyntaxError with a message like:
SyntaxError: Unexpected token } in JSON at position 42
The position number is a character offset from the beginning of the string. To find the problem, count characters from the start, or paste the JSON into a formatter that shows line numbers. The "unexpected token" tells you what character the parser hit when it expected something else. A closing brace after a comma means a trailing comma. A single quote means you used the wrong quote character.
Python (json.decoder)
Python gives more helpful error messages with line and column numbers:
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 3 column 5 (char 28)
This tells you the exact line and column. Open the file, go to line 3, column 5, and you will see the problem. Python also tells you what it expected (a comma delimiter), which makes diagnosis straightforward.
Debugging Strategies
When you have a large JSON file and the error message is not enough to pinpoint the issue, try these approaches:
- Binary search approach. Delete the second half of the JSON file and try parsing. If it succeeds, the error is in the second half. If it fails, the error is in the first half. Keep halving until you isolate the problematic section. This is the fastest way to find errors in large files.
- Use a linting tool. Tools like
jsonlint,jq, or an online JSON validator will pinpoint the exact line and character position. Many editors (VS Code, Sublime Text, JetBrains IDEs) also have built-in JSON validation that highlights errors as you type. - Pretty-print first. If the JSON is minified (all on one line), format it with proper indentation before debugging. A minified file with an error at position 15832 is nearly impossible to debug by hand. After pretty-printing, the error becomes obvious.
- Check encoding. If your JSON contains non-ASCII characters, make sure the file is saved as UTF-8 without a BOM (byte order mark). Some text editors add a BOM by default, and certain parsers choke on it.
- Validate incrementally. When building JSON programmatically, validate after each step rather than waiting until the entire document is assembled. This catches errors close to their source.
JSON5 and JSONC: Relaxed Alternatives
If you are writing configuration files and find strict JSON too restrictive, two popular alternatives exist:
- JSON5 extends JSON to allow single quotes, unquoted keys, trailing commas, comments, hexadecimal numbers, multi-line strings, and more. It is designed to be a superset of JSON that is easier for humans to write. Many tools and libraries support it, including Babel, webpack, and esbuild config files.
- JSONC (JSON with Comments) is a minimal extension that only adds support for
//and/* */comments plus trailing commas. VS Code uses JSONC for itssettings.jsonandtsconfig.jsonfiles.
These formats are great for configuration, but they are not suitable for data interchange. APIs and data storage should always use standard JSON to ensure compatibility across all parsers and languages.
Best Practices for Avoiding JSON Errors
The best way to deal with JSON errors is to prevent them in the first place. Here are practical strategies for production systems:
- Never hand-write JSON for data. Use
JSON.stringify()in JavaScript,json.dumps()in Python, or equivalent serializers in your language. These functions produce valid JSON by construction. - Validate with JSON Schema. Define the expected shape of your JSON using JSON Schema (draft 2020-12). Validate incoming data at your API boundaries before processing it. This catches not just syntax errors but also structural problems like missing required fields or wrong types.
- Use typed serialization. In TypeScript, use libraries like
zodorio-tsto parse and validate JSON into typed objects. In Python, usepydantic. This gives you compile-time safety and runtime validation in one step. - Configure your editor. Enable JSON validation in your IDE. VS Code highlights JSON errors in real time and can even validate against a JSON Schema if you specify the
$schemaproperty. - Add CI validation. In your build pipeline, run a JSON linter on all JSON files. A simple script like
find . -name "*.json" -exec python -m json.tool {} \;catches errors before they reach production. - Wrap parsing in try/catch. Always handle
JSON.parse()failures gracefully. Return a meaningful error to the user instead of crashing the application.
Fix your JSON instantly
Paste your broken JSON into our free JSON Formatter & Validator to find and fix errors instantly. Syntax errors are highlighted with line numbers and clear descriptions. No data leaves your browser.
Open JSON Formatter & Validator