js implemented JSON format string rotation

  JSON format string in turn achieve browser front end, a variety of methods, as summarized below:

  • 1. A method JS function, eval ()  

grammar:

var obj = eval ( "(" + TXT + ")");   // must be enclosed in brackets in the text, so as to avoid syntax errors

eval () is defined: eval () function computes a string, and executes the JavaScript code.

Since JSON syntax is a subset of JavaScript syntax, JavaScript function eval () can be used to convert text to JSON JavaScript object.

Note: When the string contains an expression, eval () function will be compiled and executed, the conversion will be security problems.

Reference: JSON use | newbie tutorial , JavaScript eval () function

 

  • 2. Method browser comes with an object JSON, JSON.parse ()  

grammar:

The JSON.parse (text [, Reviver])
 // text: Required, a valid JSON string. Former Resolution To ensure that your data is a standard JSON format, otherwise they will resolve the error. 
// Reviver: optional function a result of the conversion, this function is called for each member object.

JSON.parse () () safer than eval, and faster . Support major browsers: Firefox 3.5, IE 8, Chrome , Opera 10, Safari 4.

Note: IE8 compatibility mode, IE 7, IE 6, there will be compatibility problems.

Solution : introducingjson2.js(JSON official website)

<!--[if lte IE 7]>
<script src="json2.js"></script>    
<![endif]-->

json2.js key source analysis:

// paring process is divided into four steps. 
// The first step is to replace the unicode character as an escape character. 
// JS when dealing with multiple character is in question, not quietly delete them, even them as a line terminator. 
            = text String (text); 
            cx.lastIndex = 0 ;
             IF (cx.test (text)) { 
                text = text.replace (CX, function (A) {
                     return '\\ U' + 
                        ( '0000' + A. . the charCodeAt (0) .toString (16)) Slice (-4 ); 
                }); 
            } 
            
// second step as follows: 
// the In Stage The sECOND, WE RUN Against The text that Regular Expressions look 
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
 
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
//The look to that See WE Remaining are only whitespace characters or ']' or 
// ',' or ':'.. or '{' or '}' that the If IS SO, the then IS Safe The text for the eval 
 
            IF (/ ^ [\],: {} \ S] * $ / 
                    .test (text.replace ( / \\ (:? [ "\\\ / bfnrt] | U [0-9a-fA-F] {4}) / G, '@' ) 
                        .replace ( /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE ??] [+ \ -] \ D +) / G, ']' ) 
                        .replace ( ?? / (: ^ |: |,) (: \ S * \ [) + / G, '' ))) { 
 
// third step: eval command calling 
// '{' tends to have ambiguity in the js syntax: may be a block or object literal. So we used herein parentheses to avoid ambiguity                 
                j = eval ( '(' + text + '
json2.js key source

Reference: JSON.parse () | rookie tutorial , json2.js Brief (individual learning) - struggle Bird column

 

  • 3. reference to the jQuery plug-in, $ .parseJSON ()  

grammar:

.parseJSON $ (json)   // json: String type, incoming malformed JSON string may result in an abnormal

$ .ParseJSON () key source analysis:

// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
      return window.JSON.parse( data );
 }

// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
     .replace( rvalidtokens, "]" )
     .replace( rvalidbraces, "")) ) {
        return ( new Function( "return " + data ) )();
}
$ .ParseJSON () key source

Reference: jQuery.parseJSON () method | newbie tutorial , jQuery static methods parseJSON method and source code analysis - - Yang Tsai

 

  • 4.   When the requested AJAX JSON data acquisition, $ . The getJSON () 

grammar:

jQuery.getJSON (URL, Data, Success (Data, Status, XHR))
 // URL required. The provisions of which the request URL sent. 
// the Data Optional. Predetermined data sent to the server along with a request. 
// Success (the Data, Status, xhr) optional. Function defining operations when the request is successful.

This time the data has been returned JSON object, you do not need to be converted.

$ . GetJSON () is shorthand Ajax function is equivalent to:

$.ajax({
  url: url,
  data: data,
  success: callback,
  dataType: "json"
});

Reference: the jQuery Ajax - the getJSON () method

 

 to sum up:

1. recommended the JSON.parse () method; if required compatible IE7 / 6, reintroduced json2.js file. Corresponding to the JSON.stringify () method can be used to convert a string JSON object.

2. If the pages already cited jQuery, you do not want to introduce unnecessary files (json2.js), you can use $ .parseJSON () method.

3. When using the eval (), the string should be noted there are no executable code.

4. If the data is obtained by AJAX JSON, directly with $ . The getJSON () function, or add parameters in dataType $ .ajax () in: "json", can be obtained directly JSON object.

 

 

Reference: JS JSON string into a four methods of note - angels cry - blog Park

Guess you like

Origin www.cnblogs.com/coolxiaoyi/p/11251765.html