34

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

boop_the_snoot
  • 2,941
  • 3
  • 27
  • 43
Cristiano Sarmento
  • 563
  • 2
  • 8
  • 18
  • 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

11 Answers11

34

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
  • 420
  • 4
  • 7
  • 5
    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
  • 9
    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
  • @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
21

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
  • 441
  • 4
  • 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
17

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
  • 532
  • 4
  • 6
9

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
  • 20,117
  • 15
  • 137
  • 145
  • 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

-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,423
  • 17
  • 21
-1

You can use Regex.Unescape(yourEscapedString);

kritikaTalwar
  • 1,692
  • 1
  • 14
  • 24
-3

try this

json.Replace(@"\", " ")
vborutenko
  • 4,248
  • 5
  • 27
  • 46
-3

Basically you are asking how to replace the backslash in C#.

You have to use String.Replace method. The documentation tell us:

String.Replace Method (String, String)

Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.

So, your string will take the value returned by Replacemethod:

jsonString= jsonString.Replace(@"\"," ");
Ionică Bizău
  • 102,012
  • 80
  • 271
  • 450
-4

Just grab the json string and make it a String.Replace()

string JsonContentFixed = JsonContentString.Replace(@"\", " ");
Carlos Landeras
  • 10,812
  • 11
  • 54
  • 82
  • I would like to know the reason for @ symbol before the "\" `Replace(@"\", " ")` It is already a string then why is that needed? Please shed some light on this. – Praveen May 22 '13 at 13:39
  • So you dont have to use scape character for the bar "\". If you dont use @ you will have to use .Replace("\\", " "); – Carlos Landeras May 22 '13 at 13:47
-4

You can use Replace()

string variable = "{\"data\": {\"id\": \"1\",\"name\": \"jon\"}}";
Console.WriteLine(variable.Replace("\\", " "));
Praveen
  • 53,079
  • 32
  • 129
  • 156
  • 1
    This code will not compile, if you try to replace "\\" why does you variable text only contains one backslash? "you JSON \" should really be "you JSON \\". – Mo Patel May 22 '13 at 13:59