JSON.parse not having the expected behaviour

断了今生、忘了曾经 提交于 2021-02-05 04:59:47

问题


I'm trying to get a json request, sent by post, and do the JSON.parse on it. But this error happens:

Uncaught SyntaxError: Unexpected token m in JSON at position 2 at JSON.parse () at :1:19

The code below reproduces the error:

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

And that's the way I'm sending it in my post

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

Is there something wrong in the way I'm sending it?


回答1:


Your JSON string is not formatted correctly, you will have to add double quotes " for keys & values as:

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

There are many online parser available where you can validate your JSON string, I generally use http://json.parser.online.fr/ to verify my JSON whenever it requires.




回答2:


Properly formatted JSON strings have " double quotes around each key and each string value.

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



回答3:


While sending in post, Stringify the object first, Use JSON.stringify(object) and send, while retrieving JSON.parse should work fine



来源:https://stackoverflow.com/questions/49623558/json-parse-not-having-the-expected-behaviour

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!