Fix Unexpected token o in JSON at position 1 error in JS

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

Fix Unexpected token o in JSON at position 1 error #

The "Unexpected token o in JSON at position 1" error occurs when we try to JSON.parse a value that is not a valid JSON string, e.g. a native JavaScript object. To solve the error, make sure to only pass valid JSON strings to the JSON.parse method.

unexpected token o in json at position 1

Here is an example of when the error occurs:

index.js
// โ›”๏ธ Unexpected token o in JSON at position 1 JSON.parse({}); // โ›”๏ธ (if using jQuery) $.parseJSON({})

We passed a native JavaScript object to the JSON.parse method.

If the value is already a native JavaScript value (not JSON), you don't have to use the JSON.parse or $.parseJSON methods. You can use the value in your code as is.

If you're trying to convert a value to JSON, you should use the JSON.stringify() method instead:

index.js
// โœ… is now valid JSON string const json = JSON.stringify({name: 'Tom'});

If you're trying to parse a JSON string to a native JavaScript value, you have to make sure the value is valid JSON before parsing it or you can use a try/catch block to handle any errors.

If the value is JSON, then it must be of type string.

index.js
console.log(typeof {}); // ๐Ÿ‘‰๏ธ "object" console.log(typeof JSON.stringify([1])); // ๐Ÿ‘‰๏ธ "string"

Here's an example of how to use a try/catch block to handle an eventual error while parsing a JSON value.

index.js
try { const parsed = JSON.parse({}); } catch (err) { // โ›”๏ธ Unexpected token o in JSON at position 1 console.log(err.message); }

We call the JSON.parse method inside of a try/catch block. If passed an invalid JSON value, the method will throw an error, which will get passed to the catch() function.

You can handle the error in the catch function as you see fit.

If you are expecting valid JSON from your server, you can console.log the response from your server and its type using the typeof operator.

If your server is not sending valid JSON, make sure to set the Content-Type header to application/json on your server side.

You can paste the JSON value into an online JSON validator and see if it passes the test.

The validator would show you if there are any errors in the JSON and where the errors are.

If the value is malformed / not valid JSON, you would have to format it correctly before passing it to the JSON.parse method.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee