Struggling with invalid JSON? Learn how to identify and fix the most common JSON syntax errors, from missing quotes to trailing commas.
JSON (JavaScript Object Notation) is the de facto standard for data exchange on the web. It is lightweight, readable, and easy to parse. However, JSON is notoriously strict about its syntax. Even a single misplaced character will cause a parser to throw an error. Here are the most common JSON errors and how to resolve them.
The Error: `Unexpected token ] in JSON at position...`
The Cause: Unlike JavaScript arrays or objects, JSON does not allow a comma after the final element in an array or object.
The Fix: Remove the last comma.
*Invalid:*
```json
{
"name": "John",
"age": 30,
}
```
*Valid:*
```json
{
"name": "John",
"age": 30
}
```
The Error: `Unexpected token a in JSON at position...`
The Cause: All keys (property names) in a JSON object must be wrapped in double quotes (`"`). Single quotes (`'`) or unquoted keys are invalid.
The Fix: Wrap all keys in double quotes.
*Invalid:*
```json
{
name: 'John'
}
```
*Valid:*
```json
{
"name": "John"
}
```
The Error: `Unexpected token ' in JSON at position...`
The Cause: Just like keys, all string values in JSON must use double quotes. Single quotes are not supported.
The Fix: Replace single quotes with double quotes for all string values.
The Error: `Unexpected token ... in JSON`
The Cause: If your string contains a double quote, a backslash, or a control character (like a newline), it must be properly escaped.
The Fix: Use a backslash (`\`) to escape special characters. For example, a double quote inside a string should be written as `\"`.
*Invalid:*
```json
{
"quote": "He said, \"Hello!\""
}
```
*Valid:*
```json
{
"quote": "He said, \\"Hello!\\""
}
```
The Error: `Unexpected string in JSON at position...`
The Cause: Forgetting to separate elements in an array or key-value pairs in an object with a comma.
The Fix: Ensure every element (except the last one) is followed by a comma.
Debugging JSON manually can be tedious, especially with large files. To quickly find and fix syntax issues, use an online JSON Formatter and Validator. These tools will instantly pinpoint the exact line and character where the error occurred, saving you valuable development time.
Confused between a JSON Formatter and a JSON Validator? Discover the distinct purposes of these tools and when to use each in your development workflow.
Explore the differences between JSON and XML. Learn their pros, cons, and why JSON has largely replaced XML for modern web development.