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.)

Answer from Thanatos on Stack Overflow
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();
     }
Discussions

Java escape JSON String? - Stack Overflow
According to the answer here, quotes in string content need to be escaped with a JSON string. You can do that by replacing quotes with \" in Java, like so More on stackoverflow.com
🌐 stackoverflow.com
Escape JSON string in Java - Stack Overflow
And afterwards deserialize that string. GenericJson.toString produces simple JSON, but \n etc. are not escaped: ... I don't want to reinvent the wheel, so I'd like to use Jackson or an existing API, if possible. ... I was trying to avoid writing it from scratch, there's also Apache Commons method to escape JavaScript... More on stackoverflow.com
🌐 stackoverflow.com
Escape double-quotes in JSON string
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
6
1
September 29, 2021
VS Code Power Tools - JSON Escape Assistant: Don't worry about escaping any more

Woah. Veey cool tool. This would be a really great time saver

More on reddit.com
🌐 r/vscode
14
178
July 20, 2020
People also ask

How to escape JSON in Java?
In Java, you can escape JSON data using the JSONObject class from the org.json package, which provides several methods for doing so. You can escape a string and create a new string with the special characters replaced by their corresponding escape sequences by using the escape() method. To convert a JSON object to a string, use the function toString() method, which will automatically escape any special characters in the JSON data.
🌐
testmuai.com
testmuai.com › home › free tools › json escape
JSON Escape Free Online | Free online tool to convert plain JSON ...
What is Escape JSON?
JSON Escape removes offending characters that can cause parsing errors. Special characters such as quotes, newlines and backslashes will be replaced with their escaped counterparts.
🌐
testmuai.com
testmuai.com › home › free tools › json escape
JSON Escape Free Online | Free online tool to convert plain JSON ...
How does Escape JSON work?
Escape characters let you replace existing characters with new ones, which works best without throwing any error at runtime. Escapes characters of a UTF-8 encoded Unicode string by replacing them with special escape sequences. Utility allows you to escape HTML to a plain JSON format, which shows HTML text in a preformatted tag.
🌐
testmuai.com
testmuai.com › home › free tools › json escape
JSON Escape Free Online | Free online tool to convert plain JSON ...
🌐
Testmuai
testmuai.com › home › free tools › json escape
JSON Escape Free Online | Free online tool to convert plain JSON content to escaped HTML.
In Java, you can escape JSON data ... with the special characters replaced by their corresponding escape sequences by using the escape() method....
🌐
Shortc
jsonescaper.com
JSON String Escaper - Escape Online 🧰
A collection of free developer tools: UUID generator, string escapers for C, C#, Java, JavaScript, Python, Rust, and JSON. All tools run client-side with no data sent to a server. No account or installation required. 🔧🛠
🌐
Baeldung
baeldung.com › home › json › escape json string in java
Escape JSON String in Java | Baeldung
January 8, 2024 - The simplest and smallest library in our review is JSON-java also known as org.json. To construct a JSON object, we simply create an instance of JSONObject and basically treat it like a Map: JSONObject jsonObject = new JSONObject(); jsonObject.put("message", "Hello \"World\""); String payload = jsonObject.toString(); This will take the quotes around “World” and escape them:
🌐
JSON Formatter
jsonformatter.org › java-escape
Best Java Escape Characters tools to escape sequences and Strings
Escapes or unescapes a Java string removing traces of offending characters that could prevent compiling.
Find elsewhere
🌐
Java Guides
javaguides.net › p › json-escape-unescape-online-tool.html
JSON Escape / Unescape Online Tool
August 23, 2023 - This tool is designed to assist developers with escaping and unescaping JSON strings. By using this tool, one can quickly convert a standard string into its escaped JSON representation and vice versa. ... Click the "Escape" button.
🌐
@url-decode.com
url-decode.com › tool › json-escape-unescape
Free Online JSON Escape/Unescape Tool
Use this Online JSON Escape/Unescape tool to replace reserved characters in JSON with escaped ones and convert them back to their original form.
🌐
DevTools Daily
devtoolsdaily.com › json › escape
JSON Escape Online Tool
Escape JSON characters online for free. No ads, popups or nonsense, just an JSON escaper. Load JSON, escape JSON. Created for developers by developers from team Browserling.
🌐
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.
🌐
JSON Formatter
jsonformatter.org › json-escape
Best JSON Escape Characters, Double Quotes and Backslash tool
JSON Escape Characters tools to escapes double quotes, backslash, single quote and special characters
🌐
Whapi
whapi.cloud › json-string-escaper
Free JSON String Escaper Online | Easily Escape JSON Special Characters
Use our free JSON String Escaper tool to quickly escape special characters in JSON / Text strings. Perfect for developers and data processing tasks, our tool helps ensure JSON validity, making your data integration and coding smoother.
🌐
Blogger
javarevisited.blogspot.com › 2017 › 06 › how-to-escape-json-string-in-java-eclipse-IDE.html
How to Escape JSON String in Java- Eclipse IDE Tips and Example
You can escape String in Java by putting a backslash in double quotes e.g. " can be escaped as \" if it occurs inside String itself. This is ok for a small JSON String but manually replacing each double quote with an escape character for even ...
🌐
W3Docs
w3docs.com › java
How should I escape strings in JSON?
import org.apache.commons.text.StringEscapeUtils; String input = "Hello \nWorld \t\"Foo Bar\" \\Baz"; String escaped = StringEscapeUtils.escapeJson(input); System.out.println(escaped); // prints "Hello \nWorld \t\"Foo Bar\" \\Baz" ... If you are using a JSON library to generate JSON strings, such as Gson or Jackson, you don't need to manually escape the special characters.
Top answer
1 of 2
44

No additional dependencies needed: You're looking for JsonStringEncoder#quoteAsString(String).

Click for JsonStringEncoder javadoc

Example:

import com.fasterxml.jackson.core.io.JsonStringEncoder;

JsonStringEncoder e = JsonStringEncoder.getInstance();
String commands = "ls -laF\\ndu -h";
String encCommands = new String(e.quoteAsString(commands));
String o = "{commands: \"" + encCommands + "\", id: 0, timeout: 0}"

Ref: http://fasterxml.github.io/jackson-core/javadoc/2.1.0/com/fasterxml/jackson/core/io/JsonStringEncoder.html

2 of 2
5

Using Gson for serialization proved to be quite easy and bulletproof. Afterwards Apache's commons-lang3 = 3.1 escapeEcmaScript is used. In 3.2 there's also escapeJson method.

import com.google.api.client.json.GenericJson;
import com.google.api.client.util.Key;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringEscapeUtils;

public class MyJson extends GenericJson {

    @Key("commands")
    public String commands;

    public String serialize() throws IOException {
      Gson gson = new Gson();
      String g = gson.toJson(this);
      return StringEscapeUtils.escapeEcmaScript(g);
    }
}

This produces escaped JSON:

{\"commands\":\"ls -laF\\ndu -h\"}

Deserialization is then quite simple:

protected MyJson deserialize(String str) throws IOException {
    String json = StringEscapeUtils.unescapeEcmaScript(str);
    JsonObjectParser parser = (new JacksonFactory()).createJsonObjectParser();
    return parser.parseAndClose(new StringReader(json), MyJson.class);
}

The escapeEcmaScript method isn't complicated, it does following replacement:

  {"'", "\\'"},
  {"\"", "\\\""},
  {"\\", "\\\\"},
  {"/", "\\/"}

But at least is something I don't have to care about.

🌐
Example Code
example-code.com › java › json_escape_unescape_string.asp
Java JSON Escape and Unescape a String
Chilkat • HOME • Android™ • AutoIt • C • C# • C++ • Chilkat2-Python • CkPython • Classic ASP • DataFlex • Delphi DLL • Go • Java • Node.js • Objective-C • PHP Extension • Perl • PowerBuilder • PowerShell • PureBasic • Ruby • SQL Server • Swift • Tcl • Unicode C • Unicode C++ • VB.NET • VBScript • Visual Basic 6.0 • Visual FoxPro • Xojo Plugin
🌐
TutorialsPoint
tutorialspoint.com › json_simple › json_simple_escape_characters.htm
JSON.simple - Escaping Special Characters
import org.json.simple.JSONObject; public class JsonDemo { public static void main(String[] args) { JSONObject jsonObject = new JSONObject(); String text = "Text with special character /\"\'\b\f\t\r\n."; System.out.println(text); System.out.println("After escaping."); text = jsonObject.escape(text); System.out.println(text); } }
🌐
Reddit
reddit.com › r/eclipse › how to escape json string in java- eclipse ide tips and example
r/eclipse on Reddit: How to Escape JSON String in Java- Eclipse IDE Tips and Example
July 9, 2024 - News, Technical discussions, research papers and assorted things of interest related to the Java programming language NO programming help, NO learning Java related questions, NO installing or downloading Java questions, NO JVM languages - Exclusively Java