是什么导致了第三行上的错误?

Var product = [{ “名称”:“披萨”, “价格”:“10”, “数量”:“7” },{ “名称”:“Cerveja”, “价格”:“12”, “数量”:“5” },{ “名称”:“汉堡”, “价格”:“10”, “数量”:“2” },{ “名称”:“Fraldas”, “价格”:“6”, “数量”:“2” }); console.log(产品); var b = JSON.parse(products);//意外令牌o

打开控制台以查看错误


当前回答

Products是一个对象。(从对象字面量创建)

JSON.parse()用于将包含JSON符号的字符串转换为Javascript对象。

您的代码将对象转换为字符串(通过调用. tostring()),以便尝试将其解析为JSON文本。 默认的.toString()返回"[object object]",这不是有效的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"}];

改变

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是一个数组,可以直接使用:

var i, j;

for(i=0; i<products.length; i++)
  for(j in products[i])
    console.log("property name: " + j, "value: " + products[i][j]);

如果有前导空格或尾随空格,则无效。 后面和前面的空格可以被删除为

mystring = mystring.replace(/^\s+|\s+$/g, "");

删除字符串的前导或尾随空格

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

当您使用POST或PUT方法时,请确保对主体部分进行了字符串化。

我在这里记录了一个例子 https://gist.github.com/manju16832003/4a92a2be693a8fda7ca84b58b8fa7154