How to handle special characters in JSON

Source: Internet
Author: User

JSON is an effective format for AJAX applications because it enables quick conversion between JavaScript objects and string values. Because Ajax applications are ideal for sending plain text to server-side programs and receiving plain text accordingly, APIs that generate text are naturally preferable compared to APIs that cannot generate text, and JSON allows you to work with native JavaScript objects without having to worry about how to represent them.

XML can also provide similar benefits in terms of text, but several existing APIs for converting JavaScript objects to XML are not mature with JSON APIs, and sometimes you have to be cautious when creating and working with JavaScript objects to ensure that the processing you take with the XML you choose will API collaboration. For JSON, however, the situation is quite different: it handles almost all possible object types and returns you a very good representation of the JSON data. Therefore, the greatest value of JSON is that JavaScript can be really processed as a JavaScript rather than a data format language.

All the tricks you've learned about using JavaScript objects can be applied to your code without having to worry about how to turn those objects into text.

1. Enter question

When JSON passes a value, it hangs if a carriage return character is available. We can use the regular to remove the carriage return character:

$str = Preg_replace ("' ([\ r \ n]) [\s]+ '", "", $str);//Do not use regular $str = Str_replace ("\ n", "", $str);

The transferred string is not bothered by a carriage return.

By the way, log a php filter script:

<?php//$document should contain an HTML document. This example removes HTML tags, javascript code//and white space characters. Some common//HTML entities are also converted to the appropriate text. $search = Array ("' <script[^>]*?>.*?</script> ' si ',//Remove JavaScript" ' <[\/\! ") *?                 [^<>]*?> ' Si ',//Remove HTML Tags "' ([\ r \ n]) [\s]+ '",//Remove whitespace characters "' & (quot| #34); ' I ",//Replace 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 as PHP code $replace = Array ("", "", "\\1", "\" ","           & "," < "," > "," ", Chr (161),       Chr (162), Chr (163), Chr (169), Chr (\\1)); $text = Preg_replace ( $search, $replace, $document);? >
2. HTML special characters

After passing the data to the client in JSON format from the server side, some special characters cannot be displayed directly when the HTML page is displayed via JS, such as "<b>msg</b> #" displayed in the HTML page via JS when the background is passed. , not msg #, because the content between < and > is treated as an HTML tag, and the # with the & Start is HTML entity, so the display is not normal.

The solution is very simple, in JS to render it to the HTML page before the conversion can be:

<script type= "Text/javascript" > var str = ' <b>msg</b> # ';    Document.all.div1.innerhtml= ' <pre> ' +str+ ' </pre> ';      The string in JS normally appears in the HTML page string.prototype.displayhtml= function () {//Converts the string to an array of var Strarr = This.split (");      HTML page Special character display, the space is not the essence, but multiple spaces when the browser shows only one default, so replace Var htmlchar= "&<>";              for (var i = 0; i< str.length;i++) {//lookup contains special HTML characters if (Htmlchar.indexof (Str.charat (i))!=-1) {                       If present, 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

The function can handle spaces, slashes, and any other content that might affect the browser and convert them to Web-usable characters (for example, spaces are converted to%20, and the browser does not treat them as whitespace, but instead makes changes and passes them directly to the server). After that, the server will (usually automatically) convert them back to their original "face" after they are transmitted.

var url = "nowamagic.php?people=" + Escape (people.tojsonstring ()); Request.open ("GET", url, True); Request.onreadystatechange = Updatepage;request.send (null);

There are two drawbacks to this approach: when sending large chunks of data using a GET request, there is a length limit on the URL string. Although this limitation is broad, the length of the object's JSON string representation may be more than you might think, especially when using extremely complex objects. When all data is sent across the network in plain text, the security of sending data is beyond your processing power.

In short, these are the two limitations of a GET request, not just two things that are related to JSON data. When you want to send more content than your user name and last name, such as the choices in your form, you may need to be more careful. To work with any confidential or extremely long content, you can use a POST request.

4. Quotation mark Issues

If you include quotation marks or double quotes in JSON, the JSON format is broken. There are two ways to solve this.

In storage, you can use the Addslashes () function to process the string, with a slash before the quotation marks. The characters that are changed include single quotation marks ('), double quotation marks ("), backslash backslash (\), and null character null.

$text = Addslashes ($text);

JavaScript, you can do this:

To summarize here.

How to handle special characters in JSON

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.