Definition: What is a JSON Parse Error?
JSON parse error occurs when JavaScript's JSON.parse() function attempts to parse a string that is not valid JSON. The error message "Unexpected token" indicates that the parser encountered a character or sequence of characters that doesn't conform to the JSON specification at a position where it wasn't expected.
JSON (JavaScript Object Notation) has strict syntax rules: strings must use double quotes, no trailing commas, no comments, and proper escaping of special characters. When these rules are violated, JSON.parse() throws a SyntaxError with details about what went wrong and where.
Common causes include trailing commas, single quotes instead of double quotes, unescaped special characters, comments in JSON, missing quotes around keys, or invalid characters. Understanding JSON syntax rules is essential for fixing these errors.
Key Point: JSON has strict syntax rules. The "unexpected token" error indicates the parser found something that doesn't match valid JSON syntax. Always validate JSON before parsing and use try-catch blocks to handle errors gracefully.
What: Understanding JSON Parse Errors
JSON parse errors can manifest in different ways:
Unexpected Token Errors
"Unexpected token" errors occur when the parser encounters invalid characters like single quotes, trailing commas, or unescaped special characters. The error message usually indicates the position where the unexpected token was found.
Example: Unexpected token ' in JSON at position 5
Common Syntax Violations
Common violations include: trailing commas after the last item, single quotes instead of double quotes, comments (// or /* */), unescaped characters, missing quotes around keys, or invalid characters like control characters.
JSON is stricter than JavaScript object literals.
Error Object Properties
JSON parse errors are SyntaxError objects with properties like message (error description) and stack (call stack). The message often indicates the position of the error.
Error messages help identify the problem location.
Validation Tools
JSON validators can help identify syntax errors before parsing. Online validators, IDE extensions, or built-in validation can catch errors early. Always validate JSON from external sources before parsing.
Validation prevents runtime errors.
Important: JSON parse errors are syntax errors, not runtime logic errors. They occur when the JSON string doesn't conform to the JSON specification. Always validate JSON before parsing and handle errors gracefully.
When: When JSON Parse Errors Occur
JSON parse errors occur in these situations:
Parsing API Responses
When parsing JSON responses from APIs, errors occur if the response is malformed, contains invalid characters, or isn't actually JSON (e.g., HTML error pages returned as JSON).
Parsing User Input
When parsing JSON from user input (forms, text areas), errors occur if users enter invalid JSON syntax, use single quotes, add trailing commas, or include comments.
Parsing LocalStorage/File Data
When parsing JSON stored in localStorage, sessionStorage, or files, errors occur if the data was corrupted, manually edited incorrectly, or contains invalid syntax.
Stringifying and Parsing
When converting objects to JSON strings and back, errors can occur if the string was modified incorrectly, contains circular references (which JSON.stringify can't handle), or includes invalid values.
Common Scenario: JSON parse errors are most common when parsing data from external sources (APIs, user input, files) that may contain invalid JSON syntax or unexpected data formats.
How To: Step-by-Step Solutions with Examples
Follow these methods to fix JSON parse errors:
Method 1: Fix Common Syntax Errors
Remove Trailing Commas
JSON doesn't allow trailing commas. Remove commas after the last item:
// ❌ Invalid - trailing comma
const invalid = '{"name": "John", "age": 30,}';
JSON.parse(invalid); // Error: Unexpected token }
// ✅ Valid - no trailing comma
const valid = '{"name": "John", "age": 30}';
JSON.parse(valid); // Works!Use Double Quotes (Not Single Quotes)
JSON requires double quotes for strings and keys:
// ❌ Invalid - single quotes
const invalid = "{'name': 'John', 'age': 30}";
JSON.parse(invalid); // Error: Unexpected token '
// ✅ Valid - double quotes
const valid = '{"name": "John", "age": 30}';
JSON.parse(valid); // Works!Remove Comments
JSON doesn't support comments. Remove all comments:
// ❌ Invalid - contains comment
const invalid = '{"name": "John", // user name\n "age": 30}';
JSON.parse(invalid); // Error: Unexpected token /
// ✅ Valid - no comments
const valid = '{"name": "John", "age": 30}';
JSON.parse(valid); // Works!Escape Special Characters
Escape special characters in strings properly:
// ❌ Invalid - unescaped quotes
const invalid = '{"message": "He said "Hello""}';
JSON.parse(invalid); // Error: Unexpected token
// ✅ Valid - escaped quotes
const valid = '{"message": "He said \"Hello\""}';
JSON.parse(valid); // Works!
// Or use JSON.stringify for automatic escaping
const obj = {message: 'He said "Hello"'};
const valid2 = JSON.stringify(obj); // Automatically escapedMethod 2: Use Try-Catch for Error Handling
Graceful Error Handling
Always use try-catch blocks when parsing JSON:
function parseJSONSafely(jsonString) {
try {
const data = JSON.parse(jsonString);
return { success: true, data };
} catch (error) {
console.error('JSON parse error:', error.message);
return {
success: false,
error: error.message,
position: error.message.match(/position (\d+)/)?.[1]
};
}
}
// Usage
const result = parseJSONSafely('{"invalid": json}');
if (!result.success) {
console.log('Error at position:', result.position);
}Method 3: Validate JSON Before Parsing
Validation Function
Create a validation function to check JSON before parsing:
function isValidJSON(str) {
try {
JSON.parse(str);
return true;
} catch (e) {
return false;
}
}
// Usage
const jsonString = '{"name": "John"}';
if (isValidJSON(jsonString)) {
const data = JSON.parse(jsonString);
// Process data
} else {
console.error('Invalid JSON string');
}
// Or use a more detailed validator
function validateJSON(str) {
try {
JSON.parse(str);
return { valid: true };
} catch (error) {
return {
valid: false,
error: error.message,
position: error.message.match(/position (\d+)/)?.[1] || 'unknown'
};
}
}Method 4: Fix Common Issues in API Responses
Handle Non-JSON Responses
Check response content type before parsing:
async function fetchJSON(url) {
try {
const response = await fetch(url);
// Check content type
const contentType = response.headers.get('content-type');
if (!contentType || !contentType.includes('application/json')) {
throw new Error('Response is not JSON');
}
const text = await response.text();
// Validate before parsing
if (!text.trim()) {
throw new Error('Empty response');
}
return JSON.parse(text);
} catch (error) {
if (error instanceof SyntaxError) {
console.error('JSON parse error:', error.message);
} else {
console.error('Fetch error:', error.message);
}
throw error;
}
}Best Practice: Always validate JSON before parsing, use try-catch blocks for error handling, and check response content types when fetching from APIs. This prevents runtime errors and provides better user experience.
Why: Why Fix JSON Parse Errors Properly
Fixing JSON parse errors properly is important for several reasons:
Prevent Application Crashes
Unhandled JSON parse errors can crash your application. Using try-catch blocks and proper error handling ensures your application continues running even when JSON parsing fails, providing better user experience.
Better Error Messages
Proper error handling allows you to provide user-friendly error messages instead of cryptic syntax errors. You can guide users to fix their input or explain what went wrong.
Data Integrity
Validating JSON before parsing ensures data integrity. You can catch errors early, prevent invalid data from entering your system, and maintain data quality throughout your application.
Easier Debugging
Proper error handling with detailed error messages makes debugging easier. You can identify the exact position of errors, understand what went wrong, and fix issues more quickly.
Important: JSON parse errors are common but easily preventable. Always validate JSON before parsing, use try-catch blocks, and provide meaningful error messages to users. This improves application reliability and user experience.
Common JSON Parse Error Examples
Example 1: Trailing Comma
// Error: Unexpected token } in JSON at position 20
JSON.parse('{"name": "John", "age": 30,}');
// Fix: Remove trailing comma
JSON.parse('{"name": "John", "age": 30}');Example 2: Single Quotes
// Error: Unexpected token ' in JSON at position 1
JSON.parse("{'name': 'John'}");
// Fix: Use double quotes
JSON.parse('{"name": "John"}');Example 3: Unescaped Quotes
// Error: Unexpected token in JSON at position 15
JSON.parse('{"message": "He said "Hello""}');
// Fix: Escape quotes
JSON.parse('{"message": "He said \"Hello\""}');Example 4: Comments
// Error: Unexpected token / in JSON at position 15
JSON.parse('{"name": "John" // comment
}');
// Fix: Remove comments
JSON.parse('{"name": "John"}');Frequently Asked Questions
Can I use single quotes in JSON?
No, JSON requires double quotes for strings and keys. Single quotes are not valid JSON syntax. If you have single quotes, replace them with double quotes. Example: single-quoted objects are invalid, use double quotes for all strings and keys instead.
What is a trailing comma in JSON?
A trailing comma is a comma after the last item in an array or object. JSON doesn't allow trailing commas. Example: objects with trailing commas are invalid. Remove the comma. Modern JavaScript allows trailing commas, but JSON.parse() does not.
How do I handle JSON parse errors in JavaScript?
Use try-catch blocks to handle JSON parse errors gracefully. Wrap JSON.parse() in a try block and catch any SyntaxError. In the catch block, log the error message and handle it appropriately. This prevents your application from crashing and allows you to provide user-friendly error messages.
Can JSON contain comments?
No, JSON does not support comments. Comments (// or /* */) are not valid JSON syntax and will cause parse errors. If you need comments, remove them before parsing, or use a JSON5 parser (which supports comments) if appropriate for your use case.
How do I find the position of a JSON parse error?
The error message from JSON.parse() usually includes the position. You can extract it using: error.message.match(/position (\\d+)/)?.[1]. This helps identify exactly where the invalid syntax is located in your JSON string.