How to Resolve "SyntaxError: JSON.parse: unexpected character" Error in JavaScript
The SyntaxError: JSON.parse: unexpected character at line X column Y is a very common error in JavaScript. It occurs when you call JSON.parse() on a string that is not a valid JSON string. This error is the JSON parser's way of telling you, "I was reading the string and found a character that is not allowed at this position according to the strict rules of the JSON format."
This guide will explain the fundamental rules of the JSON format that often cause this error and walk you through the most common scenarios where it occurs, such as trying to parse a JavaScript object or an HTML response.
The Core Problem: What is Valid JSON?
The JSON.parse() method is extremely strict. It will only accept a string that adheres to the formal JSON specification. A JavaScript object literal might look like JSON, but it is not.
Key Rules of Valid JSON:
- Strings (both keys and values) must be enclosed in double quotes (
"). Single quotes (') are not allowed. - Object keys must be enclosed in double quotes.
- There can be no trailing commas after the last element in an array or the last property in an object.
- The text must be a single JSON value (e.g., an object
{}, an array[], a string"hello", a number123,true,false, ornull).
Any deviation from these rules will cause the "unexpected character" syntax error.
Common Causes and Their Solutions
Cause 1: Trying to Parse a JavaScript Object
This is the most frequent cause. You have data that is already a JavaScript object, and you mistakenly try to parse it.
Example of problem:
let myObject = { name: 'Alice' };
// PROBLEM: `myObject` is already an object, not a JSON string.
// This will throw the "unexpected character 'o'..." error because the
// string representation of an object is "[object Object]".
JSON.parse(myObject);
Error Output:
Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
The error occurs because JSON.parse() first coerces the object myObject into the string "[object Object]". The parser then sees the o at column 2 (after the opening [) and fails.
Solution: simply remove the JSON.parse() call. If your data is already a JavaScript object, you can use it directly.
let myObject = { name: 'Alice' };
console.log(myObject.name); // Correct: Access the property directly.
Cause 2: Using Single Quotes Instead of Double Quotes
JSON is stricter than JavaScript and does not allow single quotes for strings or keys.
Example of problem:
// PROBLEM: This string uses single quotes, which is invalid JSON.
let invalidJsonString = "{ 'name': 'Alice' }";
JSON.parse(invalidJsonString);
Error Output:
Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
The parser sees the single quote (') at column 2 and throws an error because it was expecting a double quote (").
Solution: ensure your JSON string uses double quotes. If you receive this from a source you don't control, you may need to correct it with a string replacement as a last resort.
let invalidJsonString = "{ 'name': 'Alice' }";
let validJsonString = invalidJsonString.replaceAll("'", '"');
let myObject = JSON.parse(validJsonString);
console.log(myObject.name); // Output: 'Alice'
Cause 3: Receiving HTML or Plain Text Instead of JSON
This is very common when making API calls with fetch. If your server returns an error page (which is HTML) instead of the expected JSON, response.json() (which uses JSON.parse() internally) will fail.
Example of problem:
// This can happen if the API endpoint returns a 404 or 500 error page.
fetch('https://api.example.com/data')
.then(response => response.json()) // This line will throw the error
.then(data => console.log(data))
.catch(error => console.error('Parsing failed:', error));
The parser will try to parse the HTML, see the < from <!DOCTYPE html> at column 1, and throw an "unexpected character" error.
Solution: always check if the fetch response was successful before attempting to parse it as JSON.
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Fetch or parsing failed:', error));
The Best Practice: Using a try...catch Block
Since data from external sources can be unpredictable, it is a crucial best practice to wrap any JSON.parse() call in a try...catch block. This prevents an invalid JSON string from crashing your entire application.
let myData;
let potentiallyInvalidJson = "{'key': 'value'}"; // Using single quotes
try {
myData = JSON.parse(potentiallyInvalidJson);
console.log('Parsing successful!');
} catch (error) {
console.error('Parsing failed:', error); // This block will run.
myData = {}; // Assign a default value on failure.
}
Conclusion
The SyntaxError: JSON.parse: unexpected character always means one thing: the string you are trying to parse is not valid JSON.
To solve it:
- First, ensure you are not accidentally trying to parse something that is already a JavaScript object. If so, remove the
JSON.parse()call. - If the input is a string, check it for common syntax errors:
- Are all strings and keys using double quotes?
- Are there any trailing commas?
- When fetching data, always check that the response was successful before trying to parse the body as JSON.
- Always wrap
JSON.parse()in atry...catchblock to handle potential errors gracefully.