Uncaught SyntaxError: Unexpected token with JSON.parse
第三行导致这个错误的原因是什么?
var 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(products); //unexpected token o
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, you should use:
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 [
.