javascript - 错误 "Uncaught SyntaxError: Unexpected

第三行出现这个错误的原因是什么?

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 是一个对象。 (从对象字面量创建)

JSON.parse() 用于将包含 JSON 表示法的 string 转换为 Javascript 对象。

您的代码将对象转换为字符串(通过调用 .toString()),以便尝试将其解析为 JSON 文本。
默认的.toString()返回"[object Object]",这是无效的JSON;因此错误。

关于javascript - 错误 "Uncaught SyntaxError: Unexpected token with JSON.parse",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14432165/

相关文章:

json - 从 JSON 数据生成 JSON 模式的工具

json - 在 Unix shell 脚本中以可读的 JSON 格式显示 curl 输出

jquery - 为什么每个人都为 jQuery 选择 JSON 而不是 XML?

java - HttpServletRequest 获取 JSON POST 数据

json - 在 Swift 中将字典转换为 JSON

javascript - 使用 Node.js 在 JSON 文件中写入/添加数据

c# - 如何将 C# 匿名类型序列化为 JSON 字符串?

python - 为什么我看到 "TypeError: string indices must be

java - 在 Java 中将 XML 转换为 JSON 的最快方法

python - 如何将字典转储到 JSON 文件?