How to Escape JSON String

How should I escape strings in JSON?

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

How to escape special characters in building a JSON string?

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.

How to escape a JSON string containing newline characters using JavaScript?

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

Java escape JSON String?

I would use a library to create your JSON String for you. Some options are:

  • GSON
  • Crockford's lib

This will make dealing with escaping much easier. An example (using org.json) would be:

JSONObject obj = new JSONObject();

obj.put("id", userID);
obj.put("type", methoden);
obj.put("msg", msget);

// etc.

final String json = obj.toString(); // <-- JSON string

How to escape JSON string for CSV parsing?

The correct answer here is to double quote the JSON string so this:

{ "a": 10 }

converts into this:

"{ ""a"": 10 }"


Related Topics



Leave a reply



Submit