Uncaught SyntaxError: Unexpected token with JSON.parse
Solution 1:
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.
Solution 2:
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);
Solution 3:
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 [
.
Solution 4:
I found the same issue with JSON.parse(inputString)
.
In my case the input string is coming from my server page [return of a page method].
I printed the typeof(inputString)
- it was string, still the error occurs.
I also tried JSON.stringify(inputString)
, but it did not help.
Later I found this to be an issue with the new line operator [\n]
, inside a field value.
I did a replace [with some other character, put the new line back after parse] and everything is working fine.
Solution 5:
JSON.parse is waiting for a String in parameter. You need to stringify your JSON object to solve the problem.
products = [{"name":"Pizza","price":"10","quantity":"7"}, {"name":"Cerveja","price":"12","quantity":"5"}, {"name":"Hamburguer","price":"10","quantity":"2"}, {"name":"Fraldas","price":"6","quantity":"2"}];
console.log(products);
var b = JSON.parse(JSON.stringify(products)); //solves the problem