We all have tried fetching the data from the server by hitting an API and parsing the response to show it on the website. Chances are, you might have got this error at some point, and this is a common error to get stuck.
If you run the following code you will get this error.
const emptyString = '' const emptyArray = [] console.log(JSON.parse(emptyString)) console.log(JSON.parse(emptyArray))
I got this error and tried resolving it. Gone through the answers on Stackoverflow and tried debugging the code, and while debugging it, I figured out why this occurs and how you can avoid this error.
This error is because we might be trying to parse an empty string or an empty array using JSON.parse()
And since we are trying to parse an empty string or empty array, end of string is reached before parsing the content of JSON text.
We have to make sure that the JSON we are trying to parse is valid. We might be getting either an empty array or an empty string as the response.
Another reason might be due to the Content-type header. The value of the Content-type header must be application/json.
Even if the server might be sending an empty response, we should be checking that as well.
How to Solve Error?
The easiest way to fix this error is to wrap our code inside a try/catch block which will help us in catching the error and with the help of that, we can show some error message.
const emptyString = '' const emptyArray = [] try { console.log(JSON.parse(emptyString)) console.log(JSON.parse(emptyArray)) } catch(err) { console.log(err.message); }
I hope you found this post to be helpful. Please share your thoughts in the comments section below. Would love to read your thoughts.
The post Solve Uncaught SyntaxError: Unexpected end of JSON input appeared first on The Crazy Programmer.
from The Crazy Programmer https://ift.tt/hrg7jOo
Comments
Post a Comment