How to handle special characters in JSON and special characters in JSON

Source: Internet
Author: User

How to handle special characters in JSON and special characters in JSON

JSON is a valid format for Ajax applications because it enables fast conversion between JavaScript objects and string values. Because Ajax applications are suitable for Sending plain text to server programs and receiving plain text, it is more desirable to generate text APIs than to generate text, JSON allows you to process local JavaScript objects without worrying about how to express them.

XML can also provide similar text benefits, but several existing APIs used to convert JavaScript objects into XML are not as mature as json apis; sometimes, you must exercise caution when creating and processing JavaScript objects to ensure that the processing can work with the selected XML session API. But for JSON, the situation is very different: it can process almost all possible object types, and will return you a very good JSON data representation. Therefore, the biggest value of JSON is that JavaScript can be processed as JavaScript rather than as a data format language.

All the techniques you have learned about using JavaScript objects can be applied to your code without worrying about how to convert these objects into text.

1. Questions about carriage return

When the value is passed in JSON, a carriage return will be suspended. We can use the regular expression to remove the carriage return:

$ Str = preg_replace ("'([\ r \ n]) [\ s] +'", "", $ str ); // do not use regular expressions $ str = str_replace ("\ n", "", $ str );

The transferred string is no longer troubled by carriage returns.

By the way, record a PHP filter script:

<? Php // $ document should contain an HTML document. // In this example, the HTML Tag, javascript code //, and blank characters are removed. Some common // HTML objects are converted into corresponding text. $ Search = array ("'<script [^>] *?>. *? </Script> 'si ", // remove javascript" '<[\/\!] *? [^ <>] *?> 'Si ", // remove the HTML Tag" '([\ r \ n]) [\ s] + '", // remove the blank character "'& (quot | #34);' I", // Replace the HTML Entity "'& (amp | #38);' I ", "'& (lt | #60);' I", "'& (gt | #62);' I", "'& (nbsp | #160 ); 'I ","' & (iexcl | #161); 'I ","' & (cent | #162); 'I ", "'& (pound | #163);' I", "'& (copy | #169);' I", "'& # (\ d + ); 'E "); // run $ replace = array (" "," "," \ 1 ","\"","&", "<", ">", "", chr (161), chr (162), chr (163), "chr (\ 1) "); $ text = preg_replace ( $ Search, $ replace, $ document);?>

2. Special HTML characters

After the data is transmitted to the client in JSON format on the server end, some special characters cannot be directly displayed when Javascript is displayed on the HTML page, for example, when '<B> msg </B> #' is displayed in the HTML page through JS, it is displayed as msg #, not msg #, this is because the content between <and> is regarded as an HTML Tag, And the '#' starting with '&' is an HTML Entity, so the display is abnormal.

The solution is simple. Convert it before JS renders it to the HTML page:

<Script type = "text/javascript"> var str = '<B> msg </B> #'; document. all. div1.innerHTML = '<pre>' + str + '</pre>'; // strings in js are normally displayed on the HTML page. prototype. displayHtml = function () {// convert a string to an array var strArr = this. split (''); // display of special characters on the HTML page. The space is essentially not, but only one character is displayed by default when multiple spaces exist. Therefore, replace var htmlChar =" & <> "; for (var I = 0; I <str. length; I ++) {// check whether special HTML characters, if (htmlChar. indexOf (str. charAt (I ))! =-1) {// If yes, convert them to the corresponding HTML Entity switch (str. charAt (I) {case' <': strArr. splice (I, 1, '<'); break; case '>': strArr. splice (I, 1, '>'); break; case '&': strArr. splice (I, 1, '&') ;}} return strArr. join ('');} alert (str. displayHtml (); document. all. div2.innerHTML = str. displayHtml (); </script>

3. escape () function

This function can process spaces, diagonal lines, and any other content that may affect the browser and convert them into available Web characters (for example, spaces are converted to % 20, the browser will not treat it as a space, but will not change it and pass it directly to the server ). Then, the server will (usually automatically) convert them back to their original "face" after transmission ".

var url = "nowamagic.php?people=" + escape(people.toJSONString());  request.open("GET", url, true); request.onreadystatechange = updatePage; request.send(null); 

There are two disadvantages of this method: when using GET requests to send large data blocks, there is a limit on the length of the URL string. Although this restriction is broad, the length of the object's JSON string representation may exceed your imagination, especially when using extremely complex objects. When sending all data in plain text across networks, the security of data transmission exceeds your processing capability.

In short, the above are two restrictions on GET requests, not two simple things related to JSON data. When you want to send more content beyond the user name and surname, such as the selection in the form, you may need to pay more attention to the two. To process any confidential or extremely long content, you can use POST requests.

4. quotation marks

JSON contains quotation marks or double quotation marks, which may damage the JSON format. There are two solutions.

When receiving a database, you can use the addslashes () function to process the string and add a slash before the quotation marks. The modified characters include single quotation marks ('), double quotation marks ("), backslash (\), and NULL.

$ Text = addslashes ($ text); for JavaScript, function valueReplace (v) {v = v. toString (). replace (new RegExp ('(["\"])', 'G'), "\" "); return v;} var eValue = encodeURI ($. trim (valueReplace (e. value )))

Here we will summarize.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.