Explain Codes LogoExplain Codes Logo

How should I escape strings in JSON?

java
json-libraries
string-escaping
unicode-escaping
Alex KataevbyAlex Kataev·Feb 14, 2025
TLDR

In Java, you can use the Gson library for JSON string escaping:

String toEscape = "Special chars: \" \\ / \b \f \n \r \t"; String escaped = new Gson().toJson(toEscape); System.out.println(escaped); // Prints escaped JSON string like a boss

Gson automatically takes care of standard escape sequences like \n, \", and \\, providing you with a well-formed and safe JSON string.

JSON libraries: Choose your weapon

Picking a robust JSON library is the first step towards hassle-free string escaping. In the Java ecosystem, we have a variety of these:

  • Gson from Google: For its simplicity and speed.
  • FasterXML/jackson: A high-performance, comprehensive library.
  • json-simple: For those who prefer a streamlined API.

These libraries follow the RFC 7159 guidelines, ensuring that the various potential characters in JSON are handled correctly.

Special characters: Diamonds in the rough

Unicode – A world beyond ASCII

Typically, libraries manage common escapes without any hiccups. But when dealing with Unicode characters and code points outside the BMP (Basic Multilingual Plane), some additional work might be required. Here's a quick way to manually escape Unicode by using the \uXXXX syntax:

String unicodeChar = "\uF991"; String escapedUnicode = String.format("\\u%04x", (int) unicodeChar.charAt(0)); System.out.println(escapedUnicode); // Print safely escaped unicode

Pitfalls – Handle with care

Avoid functions like StringEscapeUtilities.escapeHtml or escapeXml, as they do not escape double quotes, which are essential in JSON strings. Also, refrain from wrapping your strings in single quotes. It might seem tempting, but this practice will lead to malformed JSON.

Inspect and Validate: The final frontier

Always stay watchful for deprecation warnings in your IDE. They can shine a light on outdated solutions, helping you to avoid potential bugs. After escaping, make it a practice to validate your JSON to confirm that it's valid:

boolean isValid = org.json.JSONTokener.isValidJson(escaped); System.out.println("Is valid JSON?: " + isValid); // JSON validation: the cherry on top!

For an in-depth understanding of escaping strings properly, delve deeper into the Jettison library documentation.

Unleash the power of manual escaping

On the rare occasion when you're left without an external library, you'll have to bring out your survival skills and escape a JSON string the old-fashioned way:

public String escapeJson(String str) { StringBuilder escapedJson = new StringBuilder(); for (char c : str.toCharArray()) { switch (c) { case '\"': escapedJson.append("\\\""); break; // Double quote, prepare to be escaped! case '\\': escapedJson.append("\\\\"); break; // Backslash in JSON is like Batman in Gotham, it always needs a cover! ... // Handle other escapable characters. default: if (isControlChar(c)) { escapedJson.append(String.format("\\u%04x", (int) c)); } else { escapedJson.append(c); // An innocent character, let it pass! } } } return escapedJson.toString(); // And voila, we present you an escaped string }

This little exercise should give you a greater appreciation for the convenience that libraries offer!

Libraries: A safe bet

Modern library methods, like StringEscapeUtils#escapeJson from Apache Commons Text library or JSONObject.quote from org.codehaus.jettison.json, have been designed for effective handling of JSON strings. So, when in doubt, put your trust in the programs designed by the experts!