How to handle special characters in JSON _javascript tips

Source: Internet
Author: User

JSON is a valid format for AJAX applications because it enables fast conversion between JavaScript objects and string values. Because Ajax applications are ideal for sending plain text to server-side programs and receiving plain text, APIs that generate text are naturally preferable to APIs that do not generate text, and JSON allows you to work with local JavaScript objects without having to worry about how to represent those objects.

XML can also provide similar benefits in terms of text, but several existing APIs for translating JavaScript objects into XML do not mature with the JSON API; Sometimes you have to be extra cautious when creating and working with JavaScript objects to ensure that the processing you choose Talk API collaboration. But for JSON, the situation is quite different: it handles almost every possible object type and returns a very good JSON data representation. As a result, the greatest value of JSON is that JavaScript can really be processed as JavaScript rather than as 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. Carriage return problem

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

$str = Preg_replace ("' ([\ r \ n]) [\s]+ '", "", $str); 

 No regular 

 $str = Str_replace ("\ n", "", $str); 

The string that is turned out 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 whitespace 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

When the data is delivered to the client in JSON format from the server side, there are some special characters that cannot be displayed directly when the HTML page is displayed through JS, such as the ' <b>msg</b> # ' displayed in the HTML page through JS, as MSG # is not msg #, because the content between < and > is considered an HTML tag, and the opening of & with # is an 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 strings in JS are displayed normally in the HTML page string.prototype.displayhtml= function () {//convert string to array var Strarr = This.split (');  

   HTML page Special characters show that the space is not the essence, but multiple spaces when the browser defaults to show only one, so replace the Var htmlchar= "&<>";  

       for (var i = 0; i< str.length;i++) {//find if there is a special HTML character 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-available characters (for example, spaces are converted to%20 and browsers do not treat them as spaces, but instead change them directly to the server). Later, the server (usually automatically) converts 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: there is a length limit to the URL string when sending large chunks of data using a GET request. Although this restriction is broad, the length of the object's JSON string representation may be beyond your imagination, especially when using extremely complex objects. When you send all of your data across the network in plain text, the security of sending data is more than you can handle.

In short, these are the two limitations of GET requests, not the simple two things that are related to JSON data. When you want to send more content than your username and last name, such as a selection in a form, you may need to pay more attention. To handle any confidential or extremely long content, you can use a POST request.

4. Quotation mark question

If you include quotes or double quotes in JSON, you can break the format of JSON. There are two ways to solve this problem.

You can use the Addslashes () function to work with strings in storage, and to precede quotes with slashes. The changed characters include single quotation marks ('), double quotes ("), backslash backslash (\), and null character nulls.

 $text = Addslashes ($text); 

JavaScript, you can do this:

 function Valuereplace (v) { 

 v=v.tostring (). Replace (new RegExp (' ["]) ', ' G ')," \\\ "); 

return v; 

 } 

 var evalue = encodeURI ($.trim (Valuereplace (E.value)) 

To sum it up here.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.