41

I want to replace the "\" character from a JSON string by a empty space. How can I do that?

boop_the_snoot
  • 3,209
  • 4
  • 33
  • 44
Cristiano Sarmento
  • 633
  • 2
  • 9
  • 19
  • 1
    try 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
  • 1
    Just 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 Answers9

47

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)

Brad
  • 554
  • 4
  • 7
  • 7
    This 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
  • 12
    I 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
  • 3
    I 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(finalUnescapedJsonString);` – Johan Alzate Dec 18 '19 at 16:08
  • 1
    Doesn't work. `str = Regex.Unescape("\r \n a"); >str "\r \n a"` – WULF Jun 22 '20 at 08:15
  • 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
25

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
}
Simba
  • 489
  • 6
  • 7
  • 2
    In 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
  • 4
    Your 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
22

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);
Johan Alzate
  • 582
  • 4
  • 6
10

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>"}
Alexei - check Codidact
  • 22,016
  • 16
  • 145
  • 164
  • Doesn't work. `str = Regex.Unescape("\r \n a"); >str "\r \n a"` – WULF Jun 22 '20 at 08:14
  • 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
0

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

0

deserialize to another string then to your class

string resultString = JsonConvert.DeserializeObject<string>(content);
var result = JsonConvert.DeserializeObject<T>(resultString);

This worked for me.

Ah Sa Fa
  • 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
-1

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; }
    }
Ali Rasouli
  • 1,705
  • 18
  • 25
-1

You can use Regex.Unescape(yourEscapedString);

kritikaTalwar
  • 1,730
  • 1
  • 17
  • 25
-1

var json = System.Text.Json.JsonSerializer.Deserialize<JsonElement> (escapedJson)

Sajan Alex
  • 27
  • 3