Borislav Hadzhiev
Last updated: Jul 25, 2022
Check out my new book
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, use the JSON.stringify()
method if you need to
convert a value to JSON.
Here is an example of when the error occurs:
// ⛔️ 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.
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, use the JSON.stringify()
method
instead:
// ✅ is now valid JSON string const json = JSON.stringify({name: 'Tom'});
The JSON.stringify() method converts a native JavaScript value to a JSON string.
try/catch
block to handle any errors.If the value is JSON, then it must be of type string
.
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 a possible error
when parsing a value.
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.
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.
If the value is malformed or not valid JSON, you have to format it correctly
before passing it to the JSON.parse
method.