Solve - Unexpected end of JSON input Error in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

Solve - Unexpected end of JSON input Error #

The "Unexpected end of JSON input" error occurs when trying to parse invalid JSON using the JSON.parse or $.parseJSON functions. Trying to parse a value such as an empty array or string causes the error. To solve the error, make sure that the JSON is valid before parsing it.

unexpected end of json input error

Notice that the screenshot shows the line the error occurred on - in the example the error occurred in the index.js file on line 3.

index.js
// โ›”๏ธ Uncaught SyntaxError: Unexpected end of JSON input console.log(JSON.parse([])); // โ›”๏ธ Uncaught SyntaxError: Unexpected end of JSON input console.log(JSON.parse(''));

We passed an empty array and an empty string to the JSON.parse function and got the error. The same would be the result if you were using the $.parseJSON function.

index.js
// โ›”๏ธ Uncaught SyntaxError: Unexpected end of JSON input console.log($.parseJSON(''));

We get the error because we're trying to parse invalid JSON.

The error also occurs if you try to parse an empty response from the server or your server does not send the correct CORS headers along with the response.

If your server sends an empty response and you try to JSON.parse it, you will get an error. In this case you should remove the parsing logic.

If you're getting the value from your server, make sure the server is setting the Content-Type header to application/json.

You can solve the "Unexpected end of JSON input" error in the following 3 ways:

  • wrap your parsing logic in a try/catch block
  • make sure to return a valid JSON response from your server
  • remove the parsing logic from your code if you are expecting an empty server response

You can inspect the response of your server by opening your developer tools and clicking on your Network tab. If you click on the Response tab you will see the server's response.

browser network tab response

Here's an example of how to use a try/catch block to avoid the "Unexpected end of input" error when parsing.

index.js
try { const result = JSON.parse(''); console.log(result); } catch (err) { // ๐Ÿ‘‡๏ธ SyntaxError: Unexpected end of JSON input console.log('error', err); }

If the JSON.parse function throws an error due to parsing invalid JSON, the error is passed as a parameter to the catch function where we can handle it.

Alternatively, you can remove the call to the JSON.parse function if you know the server's response does not contain valid JSON.

You can also use an online JSON validator to check if a JSON string is valid.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee