0

hope all are good

I've read some answers about this, and trying different methods to convert a str response from an API, and can't get it work, here's the str response:

'{'status': '200. Ok', 'message': 'Request success'}'

The single quote at the beginning and the end, came from the response, I've tried with JSON.parse and get:

SyntaxError: Unexpected token ' in JSON at position 1

I slice the quotes at the beginning and the end, and get the same result. I even tried to add [] and didn't work either

Here's some code I try:

let response = "'{'status': '200. Ok', 'message': 'Request success'}'"

let setquotes = response.slice(1).slice(0, -1)
let convert_one = JSON.parse(setquotes)

// Got the SyntaxError for single quote

let setkeys = "[" + setquotes + "]"
let convert_two = JSON.parse(setquotes)

Could someone please help me! Thanks very much

Luiz Villalba
  • 149
  • 1
  • 2
  • 13
  • Fix whatever's giving you that broken input so it gives you JSON instead – CertainPerformance Dec 05 '22 at 06:07
  • 1
    This question got closed so I'll try to answer here. First of all, the str response doesn't look like a string. I mean, '{' is a string on its own, but the second ' should end the string, if you see what I'm saying. In any case, let's say your string is this: `'{'status': '200. Ok', 'message': 'Request success'}'`. You will want to remove the first and last ' so that it is then `{'status': '200. Ok', 'message': 'Request success'}`, and then, replace all ' with ", as JSON only uses ", not '. Then use JSON.parse() on the string: JSON.parse(`{"status": "200. Ok", "message": "Request success"}`). – JCollier Dec 05 '22 at 06:18
  • 1
    Sorry, the Stack Overflow community can often be harsh on those new to coding. I hope my comment answered your question. – JCollier Dec 05 '22 at 06:20
  • 1
    @JCollier Thank very much for taking some time, and explain too well the reason of my error, now I have it very clear! Thanks for all, friend – Luiz Villalba Dec 06 '22 at 02:29

0 Answers0