unexpected token

0
32


Views:
2

SyntaxError: Unexpected token

This error occurs when you are trying to parse a string to JSON and the string is not valid JSON.

it happens when you pass an invalid JSON string to JSON.parse () function.

It ({“A) starts as a valid JSON, however, the JSON is not complete. Hence it is telling ‘unexpected end of JSON input’.

// ⛔️ SyntaxError: Unexpected token u in JSON at position 0
console.log(JSON.parse(undefined));

When you pass undefined to the JSON.parse method it gets converted to a string and the first character in the string is the letter u, which is what the error message means.

Reasons for “Unexpected token u in JSON at position 0”

  • Referencing a non-existent property on an object.
  • Your server or local storage call returns an empty response.

How to handle the error Unexpected token u in JSON at position 0

try 
  const result = JSON.parse(undefined);
 catch (err) 
  //  This runs
  console.log('Error: ', err.message); // Output Error:  Unexpected token u in JSON at position 0

If you’re fetching data from a server API, console.log the response, make sure it’s a valid JSON string.

If you’re using local storage, open your browser’s console and clear the local storage.

// browser-console
localStorage.clear()

Let us know if you liked the post. That’s the only way we can improve.

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here