This article is about how to fix SyntaxError: unexpected end of JSON input in JavaScript.
The unexpected end of JSON input error usually occurs in JavaScript. it is one of the common errors that can be seen when we try to convert a JSON string to a JavaScript value or object using JSON.parse()
method.
The JSON.parse()
method parses a JSON string and constructs a JavaScript object based on the string.
Cause of the unexpected end of JSON input error
Here are some common causes of the error:
- Incomplete JSON structure: One of the main causes of this error is parsing a malformed string into JSON.parse() method.
- Missing commas or brackets: Missing characters or brackets in the JSON string. So make sure you have properly closed all the curly brackets
{ }
and square brackets[ ]
. - Passing Empty String: If you are passing an empty string in the wrong format. We should not pass an empty string as JSON.parse(
" "
), instead do this, JSON.parse({ }
).
Solution for unexpected end of JSON input Error.
Solution 1 : Make sure you write correct format of JSON:
- If you want to convert a string to JSON object, make sure it’s in JSON format inside (
' '
).
const str = '{"name":"Johnny", "age":30, "city":"California"}'
console.log(JSON.parse(str))
// output: { name: 'John', age: 30, city: 'New York' }
- If it’s an empty string, make sure you write it like this:
JSON.parse({ })
Solution 2 : Use Online Validator to fix syntax Errors in JSON Object
If you have a very big JSON file or text, that is hard to find for missing characters, you can use a online JSON validate tool , like jsonlint.com
The Online Validator check the JSON code for syntax errors and provide suggestions for fixing them. It helps to find the error quickly and resolve the error with ease.
Conclusion:
The “Uncaught SyntaxError: Unexpected end of JSON input” error can be frustrating to deal with. But if you follow the best practices using error-checking tools or use online validators to identify the error, it can be fixed quickly and efficiently.
Hope the above two solutions fixed your error 👍.
Related Topics: