【问题标题】:JSON.parse not having the expected behaviourJSON.parse 没有预期的行为
【发布时间】:2018-09-12 09:29:14
【问题描述】:

我正在尝试获取由post 发送的json 请求,并在其上执行JSON.parse。但是发生了这个错误:

未捕获的 SyntaxError:JSON 中位置 2 的意外标记 m 在 JSON.parse() 在:1:19

下面的代码重现了错误:

const string = '{ msg_reject: \'Rejeitado porque sim\', accept: 1, photo: \'FSADKJK23B1\' }'
const json = JSON.parse(string)

这就是我在post 中发送它的方式

{ msg_reject: 'Rejeitado porque sim', accept: 1, photo: 'FSADKJK23B1' }

我发送的方式有问题吗?

【问题讨论】:

标签: javascript json node.js ecmascript-6


【解决方案1】:

格式正确的 JSON 字符串在每个键和每个字符串值周围都有 " 双引号。

const string = '{ "msg_reject": "Rejeitado porque sim", "accept": 1, "photo": "FSADKJK23B1" }';
const json = JSON.parse(string);
console.log(json);

【讨论】:

    【解决方案2】:

    在 post 中发送时,首先将对象字符串化, 使用 JSON.stringify(object) 并发送,而检索 JSON.parse 应该可以正常工作

    【讨论】:

      【解决方案3】:

      您的 JSON 字符串格式不正确,您必须为键和值添加双引号 "

      const string = '{ "msg_reject": "Rejeitado porque sim", "accept": 1, "photo": "FSADKJK23B1" }';
      

      有很多在线解析器可以用来验证你的 JSON 字符串,我通常使用https://jsonformatter.org/json-parser 来验证我的 JSON。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-08
        • 2013-03-11
        • 1970-01-01
        • 1970-01-01
        • 2011-08-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多