4

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?

Adriano
  • 3,788
  • 5
  • 32
  • 53

3 Answers3

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);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
4

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

cb369
  • 7
  • 2
Anshuman Jaiswal
  • 5,352
  • 1
  • 29
  • 46
0

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

Venkata Sandeep
  • 191
  • 1
  • 12