Online Tutorials & Training Materials | STechies.com
Register Login

Uncaught SyntaxError: Unexpected end of JSON input

16 May 2020 2:33 pm || 0

A common error encountered by JavaScript programmers is the Uncaught SyntaxError: Unexpected end of JSON input. This is usually observed when the coder is trying to convert a string into a JSON Object.

We will try to understand the cause of this error and how it can be solved. Let us look at an example.

Error Code:

<html><head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
	  var jsondata = [''];
	  var jsonarray = JSON.parse(jsondata);
	  $.each(jsonarray, function(i, field){
		  $("div").append(field + " ");
      });
  });
});
</script>
</head>
<body>
<button>Get data</button>
<div></div>
</body></html>

Output:

Uncaught SyntaxError: Unexpected end of JSON input

We can observe here that the code raises the Uncaught SyntaxError: Unexpected end of JSON input.

In the program given above, the variable jsondata is assigned an empty string. In the next line, this variable is passed as an argument to the JSON.parse() method for parsing it. during parsing, it is converted into an empty string. So the end of the string is reached before parsing any possible content of the JSON text.

Let us look at the correct code.

Correct Code:

<html><head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
	  var jsondata = ['{"Site":"Stechies", "Code":"Jquery"}'];
	  var jsonarray = JSON.parse(jsondata);
	  $.each(jsonarray, function(i, field){
		  $("div").append(field + " ");
      });
  });
});
</script>
</head>
<body>
<button>Get data</button>
<div></div>
</body></html>

Here, you can see that the variable jsondata is assigned data in the form of key-value pairs - "Site": "Stechies", "Code": "Jquery". So, while parsing using the JSON.parse() method, it is not converted into an empty string and hence the Uncaught SyntaxError is avoided.