是什么导致了第三行上的错误?
Var product = [{ “名称”:“披萨”, “价格”:“10”, “数量”:“7” },{ “名称”:“Cerveja”, “价格”:“12”, “数量”:“5” },{ “名称”:“汉堡”, “价格”:“10”, “数量”:“2” },{ “名称”:“Fraldas”, “价格”:“6”, “数量”:“2” }); console.log(产品); var b = JSON.parse(products);//意外令牌o
打开控制台以查看错误
是什么导致了第三行上的错误?
Var product = [{ “名称”:“披萨”, “价格”:“10”, “数量”:“7” },{ “名称”:“Cerveja”, “价格”:“12”, “数量”:“5” },{ “名称”:“汉堡”, “价格”:“10”, “数量”:“2” },{ “名称”:“Fraldas”, “价格”:“6”, “数量”:“2” }); console.log(产品); var b = JSON.parse(products);//意外令牌o
打开控制台以查看错误
当前回答
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"}];
改变
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"}]';
其他回答
假设你知道它是有效的JSON,但你仍然得到这个。
在这种情况下,字符串中很可能存在隐藏/特殊字符,无论您从哪个来源获取它们。当你粘贴到一个验证器时,它们就丢失了——但是在字符串中它们仍然存在。这些字符虽然不可见,但会破坏JSON.parse()。
如果s是你的原始JSON,那么清理它:
// 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 characters
s = s.replace(/[\u0000-\u0019]+/g,"");
var o = JSON.parse(s);
为什么需要JSON.parse?它已经是对象数组格式了。
最好使用JSON。Stringify如下所示:
var b = JSON.stringify(产品);
JSON。parse在参数中等待一个字符串。您需要对JSON对象进行字符串化来解决这个问题。
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
我所犯的错误是将null(不知情)传递给JSON.parse()。
所以它在JSON的0号位置抛出了意外令牌n。
但是当你在JSON.parse()中传递一些不是JavaScript对象的东西时,就会发生这种情况。
当您使用POST或PUT方法时,请确保对主体部分进行了字符串化。
我在这里记录了一个例子 https://gist.github.com/manju16832003/4a92a2be693a8fda7ca84b58b8fa7154