Special Character Processing in Json data, special characters in json data
Today, I encountered a problem in the project. The data on the page suddenly failed to be displayed. After checking, I found that the Json data encountered a problem. When JSON is used to transmit data from the background to the foreground, when the data itself contains some special characters, the parsing of JSON data may fail. If the content contains "\" "Double quotation marks and" \ r \ n ", the data parsing will fail.
Differences between \ r, \ n, \ r \ n
\ N is a line feed, English is New line, indicating to move the cursor to the beginning of the line \ r is a Carriage return, English is Carriage return, indicating to move the cursor down a grid \ r \ n indicates a Carriage return line feed
Difference between "\ r \ n" and "</br>"
\ R \ n is the line feed of the output HTML code (when the html code is viewed, the line feed is generated) <br/> the line feed is output to the browser (when the page effect is viewed, the line feed is generated)
When users input content in Textarea, they sometimes enter double quotation marks, press enter, or line breaks. When they are saved, these special symbols are also saved to the database together. When obtaining the data, json parsing will result in errors
The following figure shows the problematic data:
{"Employees": [{"firstName": "Bill", "lastName": "Gates" },{ "firstName": "George carriage return", "lastName ": "Bush" },{ "firstName": "Thomas", "lastName": "Carter"}]}
How can I upload data to the page without changing the data. The idea is that the backend converts \ r \ n (Press ENTER) to <br/>, and then the front end switches <br/> back to \ r \ n
C # code:
1 public static string EncodeTextareaChar(string str)2 {3 if (str == null) return null;4 return str.Replace("\"", "\\\"").Replace("\r\n", "<br/>").Replace("\n", "<br/>").Replace("\r", "<br/>");5 }
Javascript code
1 function encodeTextarea(str) {2 str = str.replace(/</g, "<").replace(/>/g,">");3 var str = str.replace(/<br\/>/g, "\r\n");4 return str;5 }
Both languages have the replace () method, and they are slightly different,
Replace in Javascript is replaced only once. For example, if "abcaebacd" has two c, it only replaces the first, replace ("c", "s"), and the result is "absaebacd"
Replace all replace in C # ("c", "s"). The result is "absaebasd"
Note: to fully replace Javascript, replace (/c/g, "s") is required. replace (/c/g, "s") indicates the content to be replaced. g indicates the global identifier.
Why should I add this one? Str. replace (/& lt;/g, "<"). replace (/& gt;/g, ">"); changed to & lt; br/& gt;