How to escape JSON string?

Solution 1:

I use System.Web.HttpUtility.JavaScriptStringEncode

string quoted = HttpUtility.JavaScriptStringEncode(input);

Solution 2:

For those using the very popular Json.Net project from Newtonsoft the task is trivial:

using Newtonsoft.Json;

....
var s = JsonConvert.ToString(@"a\b");
Console.WriteLine(s);
....

This code prints:

"a\\b"

That is, the resulting string value contains the quotes as well as the escaped backslash.

Solution 3:

Building on the answer by Dejan, what you can do is import System.Web.Helpers .NET Framework assembly, then use the following function:

static string EscapeForJson(string s) {
  string quoted = System.Web.Helpers.Json.Encode(s);
  return quoted.Substring(1, quoted.Length - 2);
}

The Substring call is required, since Encode automatically surrounds strings with double quotes.