Uncaught SyntaxError: Unexpected token with JSON.parse
products
is an object. (creating from an object literal)
JSON.parse()
is used to convert a string containing JSON notation into a Javascript object.
Your code turns the object into a string (by calling .toString()
) in order to try to parse it as JSON text.
The default .toString()
returns "[object Object]"
, which is not valid JSON; hence the error.
Let's say you know it's valid JSON but your are still getting this...
In that case it's likely that there are hidden/special characters in the string from whatever source your getting them. When you paste into a validator, they are lost - but in the string they are still there. Those chars, while invisible, will break JSON.parse()
If s
is your raw JSON, then clean it up with:
// preserve newlines, etc - use valid JSON
s = s.replace(/\\n/g, "\\n")
.replace(/\\'/g, "\\'")
.replace(/\\"/g, '\\"')
.replace(/\\&/g, "\\&")
.replace(/\\r/g, "\\r")
.replace(/\\t/g, "\\t")
.replace(/\\b/g, "\\b")
.replace(/\\f/g, "\\f");
// remove non-printable and other non-valid JSON chars
s = s.replace(/[\u0000-\u0019]+/g,"");
var o = JSON.parse(s);
It seems you want to stringify the object. So do this:
JSON.stringify(products);
The reason for the error is that JSON.parse()
expects a String
value and products
is an Array
.
Note: I think it attempts json.parse('[object Array]')
which complains it didn't expect token o
after [
.