最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JSON.parse not having the expected behaviour - Stack Overflow

programmeradmin7浏览0评论

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?

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?

Share Improve this question edited Aug 1, 2018 at 7:51 Adriano 3,9345 gold badges35 silver badges55 bronze badges asked Apr 3, 2018 at 6:26 brubdeds brindedsbrubdeds brindeds 531 silver badge4 bronze badges 2
  • this is not a valid json so that why you are getting this error – Pankaj Bisht Commented Apr 3, 2018 at 6:47
  • Possible duplicate of in JSON, Why is each name quoted? – Patrick Roberts Commented Dec 3, 2018 at 18:55
Add a ment  | 

3 Answers 3

Reset to default 25

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);

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 https://jsonformatter/json-parser to verify my JSON whenever it requires.

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

发布评论

评论列表(0)

  1. 暂无评论