Last updated: Mar 2, 2024
Reading timeยท3 min
The "Uncaught SyntaxError: Unexpected end of input" error occurs for 3 main reasons:
JSON.parse()
or $.parseJSON
.text/html
response or no response at all from a server and trying
to parse it as JSON.The most common cause of the error is forgetting a closing parenthesis, bracket or quote.
// โ๏ธ Uncaught SyntaxError: Unexpected end of input function sum(a, b) { return a + b; // ๐๏ธ forgot the closing curly brace if (true) { // ๐๏ธ forgot the closing curly brace const arr = ['a', 'b' // ๐๏ธ forgot closing square bracket const obj = {name: 'Tom' // ๐๏ธ forgot closing curly brace
You can resolve the syntax error by adding the missing parenthesis, bracket and curly brace.
function sum(a, b) { return a + b; } // ๐๏ธ added closing curly brace if ('hi'.length === 2) { console.log('success') } // ๐๏ธ added closing curly brace const arr = ['a', 'b', 'c'] // ๐๏ธ adding closing square bracket const obj = {name: 'Tom', age: 30} // ๐๏ธ added closing curly brace
Make sure that your code is formatted properly and that you see no typos that would cause a syntax error.
The error message shows that the SyntaxError was thrown on line 4
in the
index.js
file.
The error also occurs if you try to parse an empty response from your server or
an empty string using the JSON.parse()
method.
// โ๏ธ Uncaught SyntaxError: Unexpected end of JSON input console.log(JSON.parse('')); console.log($.parseJSON(''));
JSON.parse()
.To make sure you handle this scenario, you can:
try/catch
block.You can inspect the server's response 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.
try/catch
block to handle the errorHere's an example of how to use a try/catch
block to avoid the "Unexpected end
of input" error when parsing.
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.
If the value is already parsed, you don't have to use the JSON.parse
function.
Use the typeof
operator to check the type of a value.
console.log(typeof ['a', 'b', 'c']); // ๐๏ธ object console.log(typeof 13.7); // ๐๏ธ number
If the typeof
operator returns anything other than string
, then the value is
not JSON and you shouldn't use the JSON.parse
method.
Alternatively, you can remove the call to the JSON.parse
function if you
know the server's response does not contain valid JSON.
To solve the "Uncaught SyntaxError Unexpected end of input" error:
JSON.parse()
or $.parseJSON
.