How to escape JSON string? How to escape JSON string? json json

How to escape JSON string?


I use System.Web.HttpUtility.JavaScriptStringEncode

string quoted = HttpUtility.JavaScriptStringEncode(input);


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.


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.