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);
var a= { "xx": "aa", "yy": "bb" } var nA = JSON.stringify(a, null, "\\r\\t"); var nB = JSON.stringify(nA); console.log(nB) document.getElementById("showData").value = JSON.parse(nB);
<textarea id="showData" rows="10" cols="20"></textarea>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.