Uncaught SyntaxError: Unexpected token with JSON.parse Uncaught SyntaxError: Unexpected token with JSON.parse json json

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 JSONs = 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 charss = s.replace(/[\u0000-\u0019]+/g,""); var o = JSON.parse(s);


It seems you want to stringify the object, not parse. 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 [.