escape character in json code example

Example 1: escape json in javascript

var myJSONString = JSON.stringify(myJSON);
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");
// myEscapedJSONString is now ready to be POST'ed to the server.

Example 2: js remove escape characters from json

var x = {"name":"void", "type":"O'\"Rielly"};
document.write(JSON.stringify(x, null, ' '));

Example 3: js remove escape characters from json

var x = {"name":"void", "type":"O'\"Rielly"};
document.write(JSON.stringify(x, null, '8'));