Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape json in javascript

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

  • Backspace is replaced with \b
  • Form feed is replaced with \f
  • Newline is replaced with \n
  • Carriage return is replaced with \r
  • Tab is replaced with \t
  • Double quote is replaced with \"
  • Backslash is replaced with \
like image 459
Rajesh Kumar Avatar asked Oct 17 '25 23:10

Rajesh Kumar


1 Answers

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);
like image 98
Keith Avatar answered Oct 20 '25 14:10

Keith