Need help with your JSON?
Try our JSON Formatter tool to automatically identify and fix syntax errors in your JSON. JSON Formatter tool
JSON Parser Error Messages Explained
Working with data interchange formats like JSON is common practice in web development and beyond. However, just like any language, JSON has strict rules about its syntax and structure. When these rules are broken, your application's JSON parser will throw an error. Understanding these error messages is crucial for quickly identifying and fixing issues. This guide breaks down common JSON parser errors and how to tackle them.
Why Do JSON Parsing Errors Happen?
A JSON parser is a program that reads a string of text and attempts to translate it into a structured data format (like a JavaScript object or array) based on the JSON specification (json.org). Errors occur when the input string does not conform to this specification.
Common reasons for errors include:
- Syntax Errors: Incorrect use of commas, colons, brackets, braces, quotes, etc.
- Invalid Characters: Using characters that are not allowed or not properly escaped within strings.
- Incorrect Data Types: Using non-standard representations for numbers, booleans, or null.
- Structural Issues: Unclosed objects or arrays, misplaced commas, incorrect nesting.
Common JSON Error Messages Explained
Error messages can vary slightly depending on the programming language or library you are using (e.g., JavaScript's `JSON.parse`, Python's `json.loads`, Java libraries, etc.). However, the underlying cause is usually one of a few common issues. Here are some typical messages and their meanings:
1. `SyntaxError: Unexpected token ... in JSON at position ...` (JavaScript `JSON.parse`)
This is perhaps the most common error when using `JSON.parse` in JavaScript. It means the parser encountered a character or sequence of characters that it did not expect at a specific position in the string.
- Meaning: The parser found something invalid. The "unexpected token" might be the character itself, and "position" indicates where in the string the problem occurred (0-indexed).
- Common Causes:
- Trailing commas in objects or arrays (e.g., `{"a": 1,}` or `[1, 2,]`).
- Missing commas between items in objects or arrays.
- Missing quotes around keys or string values.
- Using single quotes (`'`) instead of double quotes (`"`) for strings.
- Extra characters after the main JSON structure (e.g., `{"a": 1}extra`).
- Incorrectly escaped characters within strings (e.g., using unescaped backslashes).
- Comments (JSON does not allow comments).
- How to Fix:
- Examine the JSON string at or near the indicated position.
- Look for misplaced punctuation (commas, colons, braces, brackets).
- Ensure all keys and string values are enclosed in double quotes.
- Check for trailing commas.
- Verify special characters within strings (like backslashes or double quotes) are correctly escaped (e.g., `\\` for a backslash, `\"` for a double quote).
- Remove any comments.
- Ensure only valid JSON exists in the string.
Example of problematic JSON:
{ "name": "Alice", "age": 30, "city": "New York", // This comment is invalid }
The comment `// This comment is invalid` will cause a SyntaxError. JSON does not support comments.
Example of problematic JSON:
[ 1, 2, 3, ]
The trailing comma after `3` in the array is invalid JSON syntax and will cause an error.
2. `JSONDecodeError: Expecting property name enclosed in double quotes` (Python `json.loads`)
This error is specific to parsing JSON objects and indicates that a key was not properly enclosed in double quotes.
- Meaning: Keys in a JSON object must be strings, and strings must be enclosed in double quotes.
- Common Causes:
- Using single quotes (`'key'`).
- Not quoting the key at all (`key: "value"`).
- How to Fix:
- Ensure all keys in your JSON objects are enclosed in double quotes (`"key"`).
Example of problematic JSON:
{ 'name': "Bob", age: 25 }
Both `'name'` (single quotes) and `age` (no quotes) are invalid keys in JSON. They must be `"name"` and `"age"`.
3. `JSONDecodeError: Unterminated string starting at position ...`
This error indicates that a string value started with a double quote but never had a corresponding closing double quote, or it contained unescaped special characters that terminated the string prematurely.
- Meaning: A string literal in the JSON is not properly closed.
- Common Causes:
- Missing a closing double quote.
- Including a literal double quote (`"`) within a string without escaping it (`\"`).
- Including a literal backslash (`\`) within a string without escaping it (`\\`).
- Including newline characters directly in a string (JSON strings must be on a single line or use `\n`).
- How to Fix:
- Find the string starting near the specified position.
- Ensure it has a matching closing double quote.
- Escape any literal double quotes (`\"`) or backslashes (`\\`) within the string.
- Replace literal newlines with `\n`.
Example of problematic JSON:
{ "message": "Hello, world! This is line 2." }
The newline character directly within the "message" string is invalid. It should be escaped as `\\n`.
4. `JSONDecodeError: Extra data: line ... column ... (char ...)"`
This error means the parser successfully parsed a valid JSON value (like an object or array) but found more non-whitespace characters afterwards.
- Meaning: There's content in the string after the main JSON document has finished. A valid JSON string must contain exactly one JSON value (object, array, string, number, boolean, or null) optionally surrounded by whitespace.
- Common Causes:
- Concatenating multiple JSON objects/arrays without putting them in a surrounding array.
- Having random text or characters after the closing brace/bracket of the root element.
- How to Fix:
- Identify the end of the valid JSON structure (usually the last `}` or `]`).
- Remove any characters that appear after it, except for whitespace.
- If you intend to send multiple JSON items, enclose them within a root JSON array (e.g., `[{}, {}]`).
Example of problematic JSON:
{ "a": 1 }{ "b": 2 }
Two separate JSON objects concatenated. This is invalid JSON. To fix, put them in an array: `[{\n "a": 1\n},{\n "b": 2\n}]`.
5. `SyntaxError: Unexpected non-whitespace character after JSON at position ...`
Very similar to the "Extra data" error, indicating content after the primary JSON value.
- Meaning: The parser found text or symbols after successfully completing the parse of the root JSON structure.
- Common Causes: Same as "Extra data" error.
- How to Fix: Same as "Extra data" error.
6. `SyntaxError: Expected property name or } in JSON at position ...`
Occurs when parsing an object (`{}`) and the parser expects either a key (which must be a string) or the closing brace `}` but finds something else.
- Meaning: Inside an object, after an opening `{` or after a comma, the parser needs a key (a double-quoted string) or the closing `}`. It found neither.
- Common Causes:
- Missing a key after a comma in an object (e.g., `{"a": 1,}`).
- Putting a comma before the first key in an object (e.g., `,"a": 1}`).
- Placing a value where a key should be.
- How to Fix:
- Check the content inside objects. Ensure keys are double-quoted strings.
- Remove leading or trailing commas within objects.
- Ensure there are key-value pairs separated by colons, and pairs separated by commas.
Example of problematic JSON:
{ "a": 1, }
Trailing comma after the last key-value pair is invalid in standard JSON.
7. `SyntaxError: Expected ',' or ']' after array element in JSON at position ...`
Occurs when parsing an array (`[]`) and the parser expects either a comma `,` to separate elements or the closing bracket `]` but finds something else.
- Meaning: Inside an array, after an element, the parser needs a comma or the closing `]`. It found neither.
- Common Causes:
- Missing a comma between array elements.
- Trailing comma after the last element (e.g., `[1, 2,]`).
- How to Fix:
- Check the content inside arrays. Ensure elements are separated by commas.
- Remove trailing commas within arrays.
Example of problematic JSON:
[ 1 2 ]
Missing comma between `1` and `2`. Must be `[\n 1,\n 2\n]`.
General Debugging Tips
- Use a JSON Validator: Copy the problematic JSON string into an online JSON validator (like JSONLint or services built into many IDEs). These tools provide more detailed error messages and highlight the exact line and column where the syntax breaks.
- Check the Source: If the JSON is coming from an API, a file, or another part of your system, inspect the raw output *before* your parser receives it. Make sure the source is generating valid JSON.
- Inspect the Error Position: Pay close attention to the position or line/column number provided in the error message. The error is usually *at* that location or just before it.
- Start Small: If debugging a large JSON structure, try parsing smaller, simpler parts of it to isolate the problematic section.
- Look for Encoding Issues: Ensure the JSON string is correctly encoded, usually as UTF-8. Incorrect encoding can lead to unexpected characters that break parsing.
- Check for Non-Printable Characters: Sometimes, invisible or non-printable characters can sneak into a string and cause parsing errors.
Preventing JSON Parsing Errors
The best way to handle JSON parsing errors is to prevent them from happening in the first place.
- Use Built-in Serializers: Always use standard library functions (`JSON.stringify` in JavaScript, `json.dumps` in Python, etc.) to generate JSON strings from native data structures. These functions handle quoting, escaping, and formatting correctly. Avoid manually building JSON strings using string concatenation if possible.
- Validate Input: If receiving JSON from an external source (user input, API calls), consider validating its structure and types *after* parsing, but ensure the raw string passes a basic syntax check first.
- Handle Empty/Null Responses: Anticipate that an API might return an empty string, `null`, or non-JSON content, especially in error cases. Handle these possibilities before attempting to parse.
- Set Proper `Content-Type`: If serving JSON from an API you control, set the `Content-Type` header to `application/json`. This helps clients correctly interpret the response.
Conclusion
While JSON parsing errors can be frustrating, they are usually straightforward to diagnose once you understand the common error messages and the strict rules of the JSON format. By paying attention to syntax, using reliable generation methods, and employing validation tools, you can minimize parsing issues and build more robust applications. Remember that the error message's position indicator is your primary clue!
Need help with your JSON?
Try our JSON Formatter tool to automatically identify and fix syntax errors in your JSON. JSON Formatter tool