Need to escape the following json
{
"xx": 'a',
"yy": "bb"
}
into the following structure in javascript
{\r\n\t\"xx\": 'a',\r\n\t\"yy\": \"bb\"\r\n}
I have tried the code suggestion from this link, How to escape a JSON string containing newline characters using JavaScript?
var request = {
"xx": "aaa",
"yy": "bb"
}
var myJSONString = JSON.stringify(request);
var myEscapedJSONString = myJSONString.replace(/\\n/g, "\\n").replace(/\\'/g, "\\'").replace(/\\"/g, '\\"').replace(/\\&/g, "\\&").replace(/\\r/g, "\\r").replace(/\\t/g, "\\t").replace(/\\b/g, "\\b").replace(/\\f/g, "\\f");
but not worked, please help.
Code has to escape like the following
Not sure why you want to do this, but stringify does exactly this, no regex or anything fancy,.. just stirngify your JSON string.
I've also sliced off the quotes..
var request = {
"xx": "aaa",
"yy": "bb"
}
var myJSONString = JSON.stringify(request, null, 2);
var myEscapedJSONString = JSON.stringify(myJSONString).slice(1, -1);
console.log(myEscapedJSONString);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With