I'm trying to parse JSON object but it's showing weird behaviour. when i try to save the following, unexpected console is coming.
var abc = '[{"id": 2,"result": "MwLYo\x5C/Awp=="}]'
console.log(JSON.parse(abc))
The value of "result" key is not coming as expected. how to fix this code as I want to send exact value to the API.
CodePudding user response:
Note, \x5c
is a ascii char for \
. Hence it gets converted while printing in console. Check:
What you are doing is correct. but when you parse "MwLYo\x5C/Awp==" you will get "MwLYo/Awp==". 3 characters after \ are missing
"\" is an escape character so char coming after "\" will be automatically removed by JS. you need to avoid "\" on your string
And another solution is to replace every "backslash" with a forwardslash
CodePudding user response:
Looks like \x5C
as an ascii character, so it gets converted to its utf-8 value, which is \
.
const jsonString = '[{"id": 2,"result": "MwLYo\x5C/Awp=="}]'
console.log(JSON.parse(jsonString));
I noticed because my regex to match escape characters wasn't working.
(No \ before) ( \ ) (no \ after)
(?<!\\)(\\)(?!\\)