I finally opted for the quick and dirty trick of replacing the escaped slashes in the serialized string before sending it to the server. Luckily, JSONObject also escapes backslashes, so i must also unscape them. Now if I wanted to send "\ /" intentionally the escaped string would be "\\/" and the result of replacing is the original string as intended.

Answer from Mister Smith on Stack Overflow
🌐
FreeFormatter
freeformatter.com › json-escape.html
Free Online JSON Escape / Unescape Tool - FreeFormatter.com
Escapes or unescapes a JSON string removing traces of offending characters that could prevent parsing.
🌐
Code Beautify
codebeautify.org › json-escape-unescape
JSON Escape and JSON Unescape Online Tool
Best JSON Escape and JSON Unescape tool help to escape and unescape JSON Content which can be used to view JSON code in json file.
🌐
Baeldung
baeldung.com › home › json › escape json string in java
Escape JSON String in Java | Baeldung
January 8, 2024 - String payload = new ObjectMapper().writeValueAsString(new Payload("Hello \"World\"")); ... In cases where we have an already-escaped property and need to serialize it without any further escaping, we may want to use Jackson’s @JsonRawValue annotation on that field.
Top answer
1 of 12
622

I'm appalled by the presence of highly-upvoted misinformation on such a highly-viewed question about a basic topic.

JSON strings cannot be quoted with single quotes. The various versions of the spec (the original by Douglas Crockford, the ECMA version, and the IETF version) all state that strings must be quoted with double quotes. This is not a theoretical issue, nor a matter of opinion as the accepted answer currently suggests; any JSON parser in the real world will error out if you try to have it parse a single-quoted string.

Crockford's and ECMA's version even display the definition of a string using a pretty picture, which should make the point unambiguously clear:

The pretty picture also lists all of the legitimate escape sequences within a JSON string:

  • \"
  • \\
  • \/
  • \b
  • \f
  • \n
  • \r
  • \t
  • \u followed by four-hex-digits

Note that, contrary to the nonsense in some other answers here, \' is never a valid escape sequence in a JSON string. It doesn't need to be, because JSON strings are always double-quoted.

Finally, you shouldn't normally have to think about escaping characters yourself when programatically generating JSON (though of course you will when manually editing, say, a JSON-based config file). Instead, form the data structure you want to encode using whatever native map, array, string, number, boolean, and null types your language has, and then encode it to JSON with a JSON-encoding function. Such a function is probably built into whatever language you're using, like JavaScript's JSON.stringify, PHP's json_encode, or Python's json.dumps. If you're using a language that doesn't have such functionality built in, you can probably find a JSON parsing and encoding library to use. If you simply use language or library functions to convert things to and from JSON, you'll never even need to know JSON's escaping rules. This is what the misguided question asker here ought to have done.

2 of 12
356

A JSON string must be double-quoted, according to the specs, so you don't need to escape '.
If you have to use special character in your JSON string, you can escape it using \ character.

See this list of special character used in JSON :

\b  Backspace (ascii code 08)
\f  Form feed (ascii code 0C)
\n  New line
\r  Carriage return
\t  Tab
\"  Double quote
\\  Backslash character


However, even if it is totally contrary to the spec, the author could use \'.

This is bad because :

  • It IS contrary to the specs
  • It is no-longer JSON valid string

But it works, as you want it or not.

For new readers, always use a double quotes for your json strings.

Top answer
1 of 16
163

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
2 of 16
87

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');
};
🌐
TutorialsPoint
tutorialspoint.com › home › json_simple › json simple escape characters
JSON Simple Escape Characters
March 14, 2013 - JSONObject.escape() method can be used to escape such reserved keywords in a JSON String. Following is the example − · import org.json.simple.JSONObject; public class JsonDemo { public static void main(String[] args) { JSONObject jsonObject ...
🌐
Medium
medium.com › @learnednwhati › how-to-escape-special-characters-in-building-a-json-string-2b772d6d1194
How to escape special characters in building a JSON string? | by WhatILearned | Medium
December 3, 2019 - It doesn't need to be, because JSON strings are always double-quoted. Finally, you shouldn’t normally have to think about escaping characters yourself when programatically generating JSON (though of course you will when manually editing, say, a JSON-based config file).
🌐
Shortc
jsonescaper.com
JSON String Escaper - Escape Online 🧰
Escape JSON strings online per RFC 8259. Handles backslash sequences, control characters, and unicode escapes. 🔧🛠
Find elsewhere
🌐
JSON Formatter
jsonformatter.org › json-unescape
Best Json Unescape online tool to unescape json data
Escapes or unescapes a JSON string removing traces of offending characters that could prevent parsing.
Top answer
1 of 16
190

Ideally, find a JSON library in your language that you can feed some appropriate data structure to, and let it worry about how to escape things. It'll keep you much saner. If for whatever reason you don't have a library in your language, you don't want to use one (I wouldn't suggest this¹), or you're writing a JSON library, read on.

Escape it according to the RFC. JSON is pretty liberal: The only characters you must escape are \, ", and control codes (anything less than U+0020).

This structure of escaping is specific to JSON. You'll need a JSON specific function. All of the escapes can be written as \uXXXX where XXXX is the UTF-16 code unit¹ for that character. There are a few shortcuts, such as \\, which work as well. (And they result in a smaller and clearer output.)

For full details, see the RFC.

¹JSON's escaping is built on JS, so it uses \uXXXX, where XXXX is a UTF-16 code unit. For code points outside the BMP, this means encoding surrogate pairs, which can get a bit hairy. (Or, you can just output the character directly, since JSON's encoded for is Unicode text, and allows these particular characters.)

2 of 16
60

Extract From Jettison:

 public static String quote(String string) {
         if (string == null || string.length() == 0) {
             return "\"\"";
         }

         char         c = 0;
         int          i;
         int          len = string.length();
         StringBuilder sb = new StringBuilder(len + 4);
         String       t;

         sb.append('"');
         for (i = 0; i < len; i += 1) {
             c = string.charAt(i);
             switch (c) {
             case '\\':
             case '"':
                 sb.append('\\');
                 sb.append(c);
                 break;
             case '/':
 //                if (b == '<') {
                     sb.append('\\');
 //                }
                 sb.append(c);
                 break;
             case '\b':
                 sb.append("\\b");
                 break;
             case '\t':
                 sb.append("\\t");
                 break;
             case '\n':
                 sb.append("\\n");
                 break;
             case '\f':
                 sb.append("\\f");
                 break;
             case '\r':
                sb.append("\\r");
                break;
             default:
                 if (c < ' ') {
                     t = "000" + Integer.toHexString(c);
                     sb.append("\\u" + t.substring(t.length() - 4));
                 } else {
                     sb.append(c);
                 }
             }
         }
         sb.append('"');
         return sb.toString();
     }
🌐
Baeldung
baeldung.com › home › scripting › how to unescape json string using jq
How to Unescape JSON String Using jq | Baeldung on Linux
November 16, 2024 - This is a JSON object containing an escaped JSON string field, a format commonly used when encoding escaped JSON strings within another JSON string. This is where jq plays a role in assisting with unescaping and decoding this structure. First, we need to install the jq tool if we don’t have it already installed on the system. Next, let’s create the file delivery.json containing the previous JSON string:
🌐
JSON Formatter
jsonformatter.org › json-escape
Best JSON Escape Characters, Double Quotes and Backslash tool
JSON Escape helps to escape JSON strings by removing or encoding traces of special characters that could prevent parsing.
🌐
Microsoft Power Platform Community
powerusers.microsoft.com › t5 › Building-Flows › Escaping-JSON-Invalid-Characters › td-p › 568274
Forums | Microsoft Power Platform Community
Quickly search for answers, join discussions, post questions, and work smarter in your business applications by joining the Microsoft Dynamics 365 Community.
🌐
Jsontostring
jsontostring.com
Convert JSON to String Online
Our major goal is to make your editing process simple and effective without taking much of your time. Our JSON to String Converter tool is responsible for extracting all the string values from the JSON which means JavaScript Object Notation file. Thus, the tool ignores all the characters from the JSON and thereby leaving the Strings and Numbers in the file.
🌐
Microsoft Learn
learn.microsoft.com › en-us › answers › questions › 2120642 › how-to-remove-escape-character-in-the-output-file
How to remove escape character '//' in the output file of the JSON sink dataset - Microsoft Q&A
byName(["all.be"]) This will create a JSON array without treating it as a string. ... In the Sink transformation, configure the output file's File Pattern to write as JSON objects, not as strings.
🌐
Leapcell
leapcell.io › blog › how-to-unescape-json-strings-in-python-javascript-and-java
How to Unescape JSON Strings in Python, JavaScript, and Java | Leapcell
July 25, 2025 - This guide explores how to unescape JSON strings in Python, JavaScript, and Java. JSON unescaping involves converting escaped characters in a JSON string back to their original form.
🌐
DEV Community
dev.to › lucassha › parse-your-escaped-json-jq-and-fromjson-4cpn
Parse your escaped JSON with jq and fromjson - DEV Community
November 16, 2021 - So, we have a JSON response right now that is parseable, so let's use jq to shrink this response some: aws secretsmanager get-secret-value --secret-id arn:aws:secretsmanager:us-west-2:[account-id]:secret:testing/slack/slack_api_key-y8FHjv --profile [profile] --region us-west-2 | jq .SecretString ... Let's take it a step further and get rid of the escaped characters(for brevity's sake, I'm going to only show the jq pieces from here on): | jq '.SecretString | fromjson'
🌐
Keploy
keploy.io › home › community › json escape and unescape
JSON Escape and Unescape | Keploy Blog
June 30, 2024 - A beginner's guide to escaping and unescaping JSON strings. Learn when and why to use these methods with simple examples.