Today I learned the JQuery source code to see the method. I can parse the JSON string as follows:
Copy codeThe Code is as follows:
ParseJSON: function (data ){
If (typeof data! = "String" |! Data ){
Return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
Data = jQuery. trim (data );
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
If (/^ [/],: {}/s] * $/. test (data. replace (///(? : ["// Bfnrt] | u [0-9a-fA-F] {4})/g ,"@")
. Replace (/"[^" // n/r] * "| true | false | null | -? /D + (? : // D *)? (? : [EE] [+/-]? /D + )? /G, "]")
. Replace (/(? : ^ |: | ,)(? :/S */[) +/g ,""))){
// Try to use the native JSON parser first
Return window. JSON & window. JSON. parse?
Window. JSON. parse (data ):
(New Function ("return" + data ))();
} Else {
JQuery. error ("Invalid JSON:" + data );
}
}
The core code of this method is:
Copy codeThe Code is as follows:
(New Function ("return" + data ))();
It uses Function () constructor. The json string is passed in as the function execution data, and the function is executed immediately after the definition. At this time, the function returns a JSON object.
I did a test. Using this method to parse JSON strings is several hundred times faster than using Eval for parsing.
Copy codeThe Code is as follows:
Var jsonStr = "{";
For (var I = 0; I <10000; I ++ ){
JsonStr + = "a" + I + ":" + I + ","
}
JsonStr = jsonStr. substring (0, jsonStr. length-1 );
JsonStr + = "}";
Var date = new Date ();
Var start = date. getTime ()
// Var boj = (new Function ("return" + jsonStr ))();
Var boj = eval ("(" + jsonStr + ")");
Var date1 = new Date ();
Console.info (date1.getTime ()-start );
I used firfox test results and eval parsing took 7234 milliseconds. However, using this function took 55 milliseconds, which is amazing.