N Kaushik

Fixed- Uncaught SyntaxError Unexpected token o in JSON at position 1

September 27, 2021

How to fix Uncaught SyntaxError: Unexpected token o in JSON at position 1:

Uncaught SyntaxError: Unexpected token o in JSON at position 1 is a common error and you might have faced it while trying to parse a JSON value in JavaScript.

This error occurs if you are using JSON.parse() method to parse an invalid JSON string.

In this post, I will show you how to fix this and when it appears. But, before that, let’s see how JSON.parse() method works:

Syntax of JSON.parse:

JSON.parse method is defined as like below:

JSON.parse(text, reviver)
  • text is the string to parse.
  • reviver is an optional value. It is a function to transform the values parsed.

Exception:

It throws a SyntaxError if the string is not a valid JSON.

Fix for the error:

In our case, it is throwing SyntaxError because the input is not a valid JSON string. For example:

var student ={'name':'Alex', 'age': 10};

var data = JSON.parse(student);

If you try to run this, it will throw the error.

Javascript SyntaxError Unexpected token o in JSON at position 1

This is because, student is a JSON object. Not a JSON string.

To solve this error, we need to make sure that we are passing always a string to JSON.parse. For example, for the above program, we can use JSON.stringify to get the string representation of the object before we use JSON.parse.

var student ={'name':'Alex', 'age': 10};

var data = JSON.parse(JSON.stringify(student));

It will work.


Subscribe to my Newsletter

© 2021, nkaushik