I want to replace the "\" character from a JSON string by a empty space. How can I do that?
-
1try this http://stackoverflow.com/q/16331770/72324 – Csharp May 22 '13 at 12:57
-
Similar post here http://stackoverflow.com/questions/4253367/how-to-escape-a-json-string-containing-newline-characters-using-javascript. Check it out. – Yajuvendra Vant May 22 '13 at 13:00
-
1Just a guess but, I don't think you need to replace any chars. Probably you check the json string using your debugger (hint: use the magnifier icon to see the original text). – I4V May 22 '13 at 13:06
9 Answers
I have found that the easiest and best way to remove all escape characters from your JSON string, is to pass the string into Regex.Unescape() method. This method returns a new string with no ecapes, even \n \t etc, are removed.
See this MSDN article for more details: Regex.Unescape Method (String) (System.Text.RegularExpressions)

- 554
- 4
- 7
-
7This is the only right answer. Blindly just replacing all \ characters with empty will not work when you have \ in the json content. – richard Jul 31 '16 at 05:12
-
12I know this question is a bit old, but is there a reason why no one has suggested just deserializing the JSON as a string? Like: `var json = JsonConvert.DeserializeObject
(escapedJson);` Surely JSON serializers are built for this? – Jamie Twells Jan 24 '19 at 15:51 -
3I agree with @JamieTwells. First, deserialize to another string (unescaped string): `string unescapedJsonString = JsonConvert.DeserializeObject
(escapedJsonString);` (you can repeat this many times), then, you can deserialize, again, as a target type: `MyClass targetObject = JsonConvert.DeserializeObject – Johan Alzate Dec 18 '19 at 16:08(finalUnescapedJsonString);` -
1
-
1@WULF You're *using* escapes, but the resulting string does not *contain* escapes. Try `Regex.Unescape("\\r \\b a")`; – snarf Jun 06 '21 at 20:43
If the json object is a string, in .Net the escape "\" characters are added, should you want to clean up the json string, JObject.Parse({string}) as demonstrated in the following code snippet cleans up nicely:
var myJsonAsString = "{\"Name\": \"John\", \"LastName\": \"Doe\", \"Age\": 199 }";
var myCleanJsonObject = JObject.Parse(myJsonAsString);
Should give us a clean Json object with the escape characters removed.
{
"Name": "John",
"LastName": "Doe",
"Age": 199
}

- 489
- 6
- 7
-
2In my case, I have to do that after serialize the object. string dirty = JsonConvert.SerializeObject(jsonObject); return JObject.Parse(dirty).ToString(); – Juan Acosta Feb 21 '19 at 03:33
-
4Your original string from `var myJsonAsString` already has no `\` (backslashes) in it. To get a backslash in a string, use `"\\"`. Which will then throw, because `JObject.Parse` will consider backslashes, unless followed by a legal escape character, illegal JSON (and correctly so). – Abel Feb 21 '20 at 17:30
This type of escaped strings are usually generated when you try to encode a string of JSON into JSON a second time. This causes something like "various levels of serialization"
Solution:
- First, you need to deserialize the escaped string, but not to the target CLR type, but deserialize to another string
- Repeat deserialization to string type again, if necessary.
- Then perform final deserialization to the target type:
Code:
// Initial example json string: "\"{\\\"Property1\\\":1988,\\\"Property2\\\":\\\"Some data :D\\\"}\""
// First, deserialize to another string (unescaped string).
string unescapedJsonString = JsonConvert.DeserializeObject<string>(escapedJsonString);
// Result: "{\"Property1\":1988,\"Property2\":\"Some data :D\"}"
// Second, deserialize to another string, again (in this case is necessary)
var finalUnescapedJsonString = JsonConvert.DeserializeObject<string>(unescapedJsonString);
// {"Property1":1988,"Property2":"Some data :D"} This time prints a final, unescaped, json string:
// Finally, perform final deserialization to the target type, using the last unescaped string.
MyClass targetObject = JsonConvert.DeserializeObject<MyClass>(finalUnescapedJsonString);

- 582
- 4
- 6
-
4
-
2
-
1this does work! in my case I just needed one deserialization step, not both of them. – Salvador Sarpi Aug 14 '21 at 20:54
-
1
-
`JsonConvert.DeserializeObject
("{\"Property1\":1988,\"Property2\":\"Some data :D\"}")` gives me this error message in .NET 6: `Additional text encountered after finished reading JSON content: P. Path '', line 1, position 3.` – Aileron79 Jun 13 '23 at 11:02
Regex.Unescape()
method will work just fine in most cases, but some particular cases require custom replacements. E.g. Regex.Unescape()
will generate actual line breaks which are not supported in JSON.
Unescaped JSON:
{"comments_count":27,"comments":"<a name=\"comments\"><\/a>\n\n\t\n\t\n\t\t\n\t<div class=\"CommentsList\">\n\t\t<strong>COMENTARII<\/strong>\n\t\t"}
Regex.Unescape
{"comments_count":27,"comments":"<a name="comments"></a>
Replacements
<div class="CommentsList">
<strong>Comments</strong>
"}
Custom replacements
private string SanitizeReceivedJson(string uglyJson)
{
var sb = new StringBuilder(uglyJson);
sb.Replace("\\\t", "\t");
sb.Replace("\\\n", "\n");
sb.Replace("\\\r", "\r");
return sb.ToString();
}
{"comments_count":27,"comments":"<a name=\"comments\"><\/a>\n\n\t\n\t\n\t\t\n\t<div class=\"CommentsList\">\n\t\t<strong>COMENTARII<\/strong>"}

- 22,016
- 16
- 145
- 164
-
-
2@WULF looks like you added that comment to every answer that mentioned Regex.Unescape, whereas this answer explicitly calls out `\r` `\n` and `\t` as characters that it doesn't process. – TheXenocide Mar 16 '21 at 21:07
C# string assignment does that for you, although if name or value contains \ it will be double escaped. The proper way is to use variable.Replace("\\\\","\\"); or variable.Replace(@"\\",@"\"); This will remove double escaped \ character, Leaving REQUIRED \ in value. for example if JSON contains "Domain\Username" this will be returned as \"Domain\\\\Username\" assigning that to string will result you will have Domain\\Username

- 1
- 2
deserialize to another string then to your class
string resultString = JsonConvert.DeserializeObject<string>(content);
var result = JsonConvert.DeserializeObject<T>(resultString);
This worked for me.

- 171
- 1
- 10
-
How is this different from [this answer](https://stackoverflow.com/a/54430289/70345) posted in 2019? – Ian Kemp May 17 '23 at 16:27
In c# you have only one way to create standard JSON result:
You must be add one class with your custom property name and then return Json(myClassForJsonResult) as bottom code:
public ActionResult testJsonData()
{
var myClassForJsonResult=new YourClassOfYourCustomProperties();
myClassForJsonResult.FirstPropertyStringType="first";
myClassForJsonResult.SecondPropertyIntType=2;
return Json(myClassForJsonResult);
}
class Defination:
public class YourClassOfYourCustomProperties
{
public string FirstPropertyStringType{ get; set; }
public int SecondPropertyIntType{ get; set; }
}

- 1,705
- 18
- 25
var json = System.Text.Json.JsonSerializer.Deserialize<JsonElement> (escapedJson)

- 27
- 3