Solve - Unexpected end of JSON input Error in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Check out my new book

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 methods. Trying to parse a value such as an empty array or a 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 where the error occurred. 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 method and got the error. The same would be the result if you were using the $.parseJSON method.

index.js
// ⛔️ Uncaught SyntaxError: Unexpected end of JSON input console.log($.parseJSON(''));

We got 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 when 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 method throws an error due to parsing invalid JSON, the error is passed as a parameter to the catch method where we can handle it.

Alternatively, you can remove the call to the JSON.parse method 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.

Use the search field on my Home Page to filter through my more than 3,000 articles.