“Unexpected token o in json at position 1” Error In JavaScript – How To Solve It?

unexpected token o in json at position 1 error in js

Unexpected token o in json at position 1″ in Javascript is a common error related to parsing json as an object. The below explanations can help you know more about the causes of this error and solutions.

How does this error happen?

Basically JSON.parse() is a method that converts a string to a JavaScript object or array. The error “unexpected token o in json at position 1″ in js indicates that the JSON.parse() method is being called on an object that is not of type string, it can be other types such as undefined, array or even already object type (JSON). 

For example, calling the JSON.parse() method on array type will cause this error:

let a = ['o'];
console.log(JSON.parse(a));

Here is another example of using this method on a string type, but not represent a correct JSON format for parsing:

let b = '[o",2,3]';
console.log(JSON.parse(b));

How to solve the error “unexpected token o in json at position 1″ in js?

Method 1: Convert variable to a JSON string

You must convert an array into a JSON string, as we have explained above, to use the JSON.parse() method. However, it would help if you remembered not to use the toString() method as it would return a string of text, not a string representing an array object.

let a = '[1,2,3]'; 
console.log(JSON.parse(a));

Output:

(3) [1, 2, 3]

We used the approach of inserting a quote character within the brackets of the array, which is one of the most efficient ways of converting an array into JSON string. But also remember that if you want to convert any type (even object) into a JSON string, just use the JSON.stringify() method. For instance:

let a = [1,2,3]; 
let b = JSON.stringify(a);
console.log(JSON.parse(b));

Output:

(3) [1, 2, 3]

Method 2: Remove the JSON.parse() method and use the object

Another way to overcome this problem is to check your parameter value passed to the JSON.parse(), if it is already a JSON object, then all you have to do is get rid of the JSON.parse() usage as you already have the JSON object.

let arr = [1,2,3];
console.log(arr) // instead console.log(JSON.parse(arr))
let obj = {url : "learnshareit.com"};
console.log (obj) // instead console.log(JSON.parse(obj))

Output:

(3) [1, 2, 3]
{url: 'learnshareit.com'}

Summary

We have learned how to deal with the error “unexpected token o in json at position 1” in javascript. By checking the correct type and format before calling the JSON.parse() method, you can easily avoid this error.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *