Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing escape characters from JSON

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

like image 779
Cristiano Sarmento Avatar asked May 22 '13 12:05

Cristiano Sarmento


People also ask

How remove all escape characters from JSON string?

replaceAll("\\","");

Does JSON need escape characters?

You can find a JSON library in your language that you can feed some appropriate data structure to, and let it work for you. In JSON the only characters you must escape are \, ", and control codes.

What is escape character in JSON?

Escapes or unescapes a JSON string removing traces of offending characters that could prevent parsing. The following characters are reserved in JSON and must be properly escaped to be used in strings: Backspace is replaced with \b. Form feed is replaced with \f. Newline is replaced with \n.

What is an escape character in JSON?

Escapes or unescapes a JSON string removing traces of offending characters that could prevent parsing. The following characters are reserved in JSON and must be properly escaped to be used in strings: Backspace is replaced with b. Form feed is replaced with f. Newline is replaced with n.

What characters are reserved in JSON strings?

The following characters are reserved in JSON and must be properly escaped to be used in strings: Backspace is replaced with \b. Form feed is replaced with \f. Newline is replaced with \n. Carriage return is replaced with \r. Tab is replaced with \t. Double quote is replaced with \". Backslash is replaced with \\.

How to escape invalid characters from a JSON field?

The Description field I was passing has characters that JSON considers invalid characters. In order to use those characters they have to be escaped. typically with a backslash. Anyway, it was simple replace operation, although I used multiple compose.

Do I need to escape from a JSON string?

If you simply use language or library functions to convert things to and from JSON, you'll never even need to know JSON's escaping rules. This is what the misguided question asker here ought to have done. A JSON string must be double-quoted, according to the specs, so you don't need to escape '.


1 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)

like image 97
Brad Avatar answered Oct 03 '22 14:10

Brad