Skip to main content

Posts

Showing posts with the label The Crazy Programmer Solve Uncaught SyntaxError: Unexpected end of JSON input Solve Uncaught SyntaxError: Unexpected end of JSON input The Crazy Programmer

Solve Uncaught SyntaxError: Unexpected end of JSON input Pratik Sah The Crazy Programmer

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. Anothe