Register Login

'Unexpected token o in json at position 1' error – How to fix it?

Updated Nov 21, 2020

JavaScript programmers have encountered the “unexpected token o in json at position 1” at some point in their lives. This error is raised when you use the JSON.parse() method to parse a JSON string that is already parsed.

In this post, we will learn more about this issue and also a way out.

How to fix the “Uncaught SyntaxError: Unexpected token o in JSON at position 1”?

If a JSON string is already parsed in a JavaScript object, the JSON.parse() cannot work on it anymore. This is because this method expects you to pass a simple string, and anything else will crash the code.

Error code

<script type="text/javascript">

      var customer_details ={"cust_id":10,"title":"jlkjlkjlkjljl"};

      var name_list = JSON.parse(customer_details);

      document.write(name_list['title']);

</script>

This code will throw the Uncaught Syntax error.

Solution     

Use the JSON.stringify() method to remove the error. This will convert the data into a string before parsing it.

For example,

var string1 = JSON.stringify(data);

var parsed = JSON.parse(string1);  

 


×