216

I have to form a JSON string in which a value is having new line character. This has to be escaped and then posted using AJAX call. Can any one suggest a way to escape the string with JavaScript. I am not using jQuery.

5
  • 3
    I tried escaping the new line character \n to \\n. It is working fine. But i am looking for any JS library which can do this for all the escape characters.
    – Srikant
    Nov 23, 2010 at 6:40
  • 1
    Why do you need to escape the newlines within the JSON? How are these values being decoded when they're used, because the appropriate solution is to use the related encoding function.
    – zzzzBov
    Oct 4, 2013 at 20:41
  • i spent 6 hours trying all kinds of things with tons of variations only to discover a tiny additional slash would make it all work like magic the things i thought were hard took like 5 mins...the thing i thought was given became the impossible..omg Mar 2, 2014 at 17:19
  • 1
    When you use Ajax-calls with Server-Side php-db-saving, just use the php-function addslashes() to convert it. With this solution you only have one place to convert and its cleaner than the javascript-replace lines. Feb 12, 2015 at 16:21
  • 1

17 Answers 17

160

Take your JSON and .stringify() it. Then use the .replace() method and replace all occurrences of \n with \\n.

EDIT:

As far as I know of, there are no well-known JS libraries for escaping all special characters in a string. But, you could chain the .replace() method and replace all of the special characters like this:

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. 

But that's pretty nasty, isn't it? Enter the beauty of functions, in that they allow you to break code into pieces and keep the main flow of your script clean, and free of 8 chained .replace() calls. So let's put that functionality into a function called, escapeSpecialChars(). Let's go ahead and attach it to the prototype chain of the String object, so we can call escapeSpecialChars() directly on String objects.

Like so:

String.prototype.escapeSpecialChars = function() {
    return this.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");
};

Once we have defined that function, the main body of our code is as simple as this:

var myJSONString = JSON.stringify(myJSON);
var myEscapedJSONString = myJSONString.escapeSpecialChars();
// myEscapedJSONString is now ready to be POST'ed to the server
13
  • 3
    Thanks alex. I have to do this for all the escape characters right? Is there is any JS library to do this?
    – Srikant
    Nov 23, 2010 at 6:44
  • 5
    This is the exact function which solved my problem String.prototype.escapeSpecialChars = function() { return this.replace(/\\/g, "\\\\"). replace(/\n/g, "\\n"). replace(/\r/g, "\\r"). replace(/\t/g, "\\t"). replace(/\f/g, "\\f"). replace(/"/g,"\\\""). replace(/'/g,"\\\'"). replace(/\&/g, "\\&"); }
    – Srikant
    Nov 23, 2010 at 9:32
  • 11
    As noted in the answer by user667073, there are a few errors in this solution. See json.org - & and ' must not be escaped. Nov 15, 2011 at 22:07
  • 5
    I had to down-vote this since the regular expressions seem to be wrong. I tried to use it, but had to fix the regular expressions by removing one of the slashes, for example: /\\n/g should be /\n/g. See "Non-Printable Characters" at this link for details - RegExp Info
    – b01
    Mar 1, 2013 at 16:24
  • 2
    In order to also escape backslashes, add .replace(/\\/g, "\\\\"). It's kind of sad that we have to do it this way and there isn't a function provided by js.
    – jakob.j
    Jan 14, 2019 at 10:17
86

As per user667073 suggested, except reordering the backslash replacement first, and fixing the quote replacement

escape = function (str) {
  return str
    .replace(/[\\]/g, '\\\\')
    .replace(/[\"]/g, '\\\"')
    .replace(/[\/]/g, '\\/')
    .replace(/[\b]/g, '\\b')
    .replace(/[\f]/g, '\\f')
    .replace(/[\n]/g, '\\n')
    .replace(/[\r]/g, '\\r')
    .replace(/[\t]/g, '\\t');
};
4
  • 5
    You don't have to do all of these. Only backslash, newline, linefeed, and the two quotes. And it's missing: Single quote, Line separator \u2028 and Paragraph separator \u2029. Ref: es5.github.io/#x7.3
    – Ariel
    May 12, 2013 at 20:43
  • 2
    Nice, but why are the square brackets necessary and not: escape = function (str) { return str .replace(/\\/g, '\\\\') .replace(/\"/g, '\\\"') .replace(/\//g, '\\/') .replace(/\b/g, '\\b') .replace(/\f/g, '\\f') .replace(/\n/g, '\\n') .replace(/\r/g, '\\r') .replace(/\t/g, '\\t'); }; Nov 27, 2015 at 20:27
  • 5
    perfect. the accepted answer (above this one) simply doesn't work. using nodeJS. Sep 4, 2016 at 9:34
  • I get this error: Uncaught SyntaxError: Unexpected token \ in JSON at position 2
    – Pathros
    Feb 7, 2017 at 15:42
41

Like you, I have been looking into several comments and post to replace special escape characters in my JSON which contains html object inside that.

My object is to remove the special characters in JSON object and also render the html which is inside the json object.

Here is what I did and hope its very simple to use.

First I did JSON.stringify my json object and JSON.parse the result.

For eg:

JSON.parse(JSON.stringify(jsonObject));

And it solves my problem and done using Pure Javascript.

5
  • 4
    This is definitely the way to go May 14, 2016 at 4:17
  • 1
    This is definitely the way to go!
    – MartianE
    Oct 1, 2018 at 19:52
  • 2
    This is definitely will break on complex and large objects with stackoverflow error
    – AaA
    Oct 3, 2018 at 6:39
  • 1
    try JSON.parse(JSON.stringify($("body"))) in an html file with body and some few tables. $("body") is a javascript object but stringify will fail parsing it.
    – AaA
    Oct 8, 2018 at 6:54
  • I will check your query and revert. Oct 8, 2018 at 15:38
28

I'm afraid to say that answer given by Alex is rather incorrect, to put it mildly:

  • Some characters Alex tries to escape are not required to be escaped at all (like & and ');
  • \b is not at all the backspace character but rather a word boundary match
  • Characters required to be escaped are not handled.

This function

escape = function (str) {
    // TODO: escape %x75 4HEXDIG ?? chars
    return str
      .replace(/[\"]/g, '\\"')
      .replace(/[\\]/g, '\\\\')
      .replace(/[\/]/g, '\\/')
      .replace(/[\b]/g, '\\b')
      .replace(/[\f]/g, '\\f')
      .replace(/[\n]/g, '\\n')
      .replace(/[\r]/g, '\\r')
      .replace(/[\t]/g, '\\t')
    ; };

appears to be a better approximation.

1
  • 6
    actually you should change the order to replace the backslashes before the double quotes, or else you'll end up with \\\\". Also the quote line should be .replace(/[\"]/g, '\\\"')
    – Ryan
    Feb 1, 2012 at 4:06
12

A small update for single quotes

function escape (key, val) {
    if (typeof(val)!="string") return val;
    return val      
        .replace(/[\\]/g, '\\\\')
        .replace(/[\/]/g, '\\/')
        .replace(/[\b]/g, '\\b')
        .replace(/[\f]/g, '\\f')
        .replace(/[\n]/g, '\\n')
        .replace(/[\r]/g, '\\r')
        .replace(/[\t]/g, '\\t')
        .replace(/[\"]/g, '\\"')
        .replace(/\\'/g, "\\'"); 
}

var myJSONString = JSON.stringify(myJSON,escape);
8

this is an old post. but it may still be helpful for those using angular.fromJson, and JSON.stringify. escape() is deprecated. use this instead,

var uri_enc = encodeURIComponent(uri); //before you post the contents
var uri_dec = decodeURIComponent(uri_enc); //before you display/use the contents.

ref http://www.w3schools.com/jsref/jsref_decodeuricomponent.asp

1
  • stringify already does all the escaping for you -- I'm curious why not just use that? git.io/vglq7
    – Ben Davis
    Feb 6, 2016 at 15:41
6

There is also second parameter on JSON.stringify. So, more elegant solution would be:

function escape (key, val) {
    if (typeof(val)!="string") return val;
    return val
      .replace(/[\"]/g, '\\"')
      .replace(/[\\]/g, '\\\\')
      .replace(/[\/]/g, '\\/')
      .replace(/[\b]/g, '\\b')
      .replace(/[\f]/g, '\\f')
      .replace(/[\n]/g, '\\n')
      .replace(/[\r]/g, '\\r')
      .replace(/[\t]/g, '\\t')
    ; 
}

var myJSONString = JSON.stringify(myJSON,escape);
6

This is an old question but the solution did not work well for me as it did not solve all cases. I finally found an answer that did the job here

I will post my combined solution of both using escape and encode uri component:

// implement JSON stringify serialization
JSON.stringify = JSON.stringify || function (obj) {
    var t = typeof (obj);
    if (t != "object" || obj === null) {
        // simple data type
        if (t == "string") obj = '"'+obj+'"';
        return String(obj);
    }
    else {
        // recurse array or object
        var n, v, json = [], arr = (obj && obj.constructor == Array);
        for (n in obj) {
            v = obj[n]; t = typeof(v);
            if (t == "string") v = '"'+v+'"';
            else if (t == "object" && v !== null) v = JSON.stringify(v);
            json.push((arr ? "" : '"' + n + '":') + String(v));
        }
        var rawString = (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
       return rawString;
    }
};
function escape (key, val) {
    if (typeof(val)!="string") return val;

    var replaced = encodeURIComponent(val);
    return replaced;
}

JSON.stringifyEscaped = function(obj){
    return JSON.stringify(obj,escape);
}
1
  • 1
    Maybe remove the double quotes around the string afterwards too? escape = (string) -> JSON.stringify(string)[1...-1]
    – Radek
    Oct 1, 2013 at 15:20
4

RegExp single line, use this function:

function escapeJSON(string) {
    return string.replace(/[\n"\&\r\t\b\f]/g, '\\$&');
}
3

I got same situation in one of my Ajax calls, where JSON was throwing an error due to the newline in the Textarea field. The solution given here didn't worked for me. So i used Javascript's .escape function and it worked fine. Then to retrieve the value from JSON, I just unescaped using .unescape.

1
  • Using Ajax calls, i prefer to use php-function newStr = addslashes(str), then save to db. So i dont have to convert at javascript-(client)-side. With this solution you need only one place to convert the slashes. Im very happy with this solution. Feb 12, 2015 at 16:17
3

It's better to use JSON.parse(yourUnescapedJson);

3

Use json_encode() if your server side scripting lang is PHP, json_encode() escapes the newline & other unexpected tokens for you (if not using PHP look for similar function for your scripting language)

then use $.parseJSON() in your JavaScript, done!

1
  • If passing data from php to javascript as JSON string, check this answer - double escaping, helped me to pass JSON.parse and convert json string to object. <script> windows.data_from_php = <?php echo json_encode(json_encode($arrayOrObjToJs)); ?>; var phpData = JSON.parse(windows.data_from_php); </script> php JSON.parse double encode Nov 19, 2014 at 10:08
3

EDIT: Check if the api you’re interacting with is set to Content-Type: application/json, &/or if your client http library is both stringify-ing and parsing the http request body behind the scenes. My client library was generated by swagger, and was the reason I needed to apply these hacks, as the client library was stringifying my pre-stringified body (body: “jsonString”, instead of body: { ...normal payload }). All I had to do was change the api to Content-Type: text/plain, which removed the JSON stringify/parsing on that route, and then none of these hacks were needed. You can also change only the "consumes" or "produces" portion of the api, see here.

ORIGINAL: If your Googles keep landing you here and your api throws errors unless your JSON double quotes are escaped ("{\"foo\": true}"), all you need to do is stringify twice e.g. JSON.stringify(JSON.stringify(bar))

2
  • Thanks @jasonco, but not really. This question is a decade old! Check my edit, it may help you.
    – Andrew
    Dec 19, 2020 at 0:56
  • hi @Andrew, thanks! still your original answer helped me, at least for what I was doing, which was also a bit hacky :)
    – jasonco
    Dec 21, 2020 at 20:32
2

I used the built in jQuery.serialize() to extract the value from a textarea to urlencode the input. The pro part is that you don't have to search replace every special char on your own and i also keep the newlines and escapes html. For serialize to work it seems the input field needs to have a name attribute though and it also adds same attribute to the escaped string which needs to be replaced away. Might not be what you are looking for but it works for me.

var myinputfield = jQuery("#myinputfield"); 
var text = myinputfield.serialize();
text = text.replace(myinputfield.attr('name') + '=','');
0
1

When using any form of Ajax, detailed documentation for the format of responses received from the CGI server seems to be lacking on the Web. Some entries here point out that newlines in returned text or json data must be escaped to prevent infinite loops (hangs) in JSON conversion (possibly created by throwing an uncaught exception), whether done automatically by jQuery or manually using Javascript system or library JSON parsing calls.

In each case where programmers post this problem, inadequate solutions are presented (most often replacing \n by \\n on the sending side) and the matter is dropped. Their inadequacy is revealed when passing string values that accidentally embed control escape sequences, such as Windows pathnames. An example is "C:\Chris\Roberts.php", which contains the control characters ^c and ^r, which can cause JSON conversion of the string {"file":"C:\Chris\Roberts.php"} to loop forever. One way of generating such values is deliberately to attempt to pass PHP warning and error messages from server to client, a reasonable idea.

By definition, Ajax uses HTTP connections behind the scenes. Such connections pass data using GET and POST, both of which require encoding sent data to avoid incorrect syntax, including control characters.

This gives enough of a hint to construct what seems to be a solution (it needs more testing): to use rawurlencode on the PHP (sending) side to encode the data, and unescape on the Javascript (receiving) side to decode the data. In some cases, you will apply these to entire text strings, in other cases you will apply them only to values inside JSON.

If this idea turns out to be correct, simple examples can be constructed to help programmers at all levels solve this problem once and for all.

1

Looks like this is an ancient post really :-) But guys, the best workaround I have for this, to be 100% that it works without complicated code, is to use both functions of encoding/decoding to base64. These are atob() and btoa(). By far the easiest and best way, no need to worry if you missed any characters to be escaped.

George

2
  • Since I came up with the same solution. I wonder if someone could clarify this solution and wheter there are some hidden caveats. Thanks.
    – mahish
    Jul 19, 2018 at 16:05
  • @mahish a little late to the party, but you have to worry about characters outside the 'Latin1' range like ✓ à la mode You can encodeURIComponent and you won't get the JavaScript error, but you'll lose the higher numbered unicode characters when you call revert the data back. So to encode: var b = btoa(encodeURIComponent(q).replace(/%([0-9A-F]{2})/g, function (m, p1) { return String.fromCharCode('0x' + p1) })) To decode: var u = decodeURIComponent(escape(atob(b))) Most of this was from stack overflow answers from various questions. Oct 7, 2021 at 13:22
-1

Use encodeURIComponent() to encode the string.

Eg. var myEscapedJSONString = encodeURIComponent(JSON.stringify(myJSON));

You don't need to decode it since the web server automatically do the same.

Not the answer you're looking for? Browse other questions tagged or ask your own question.