Today learning jquery source to see the method, the original can also parse the JSON string:
Copy Code code 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 (Data.replace (///(?: ["////bfnrt]|u[0-9a-fa-f]{4})/g," @ ")/^[/],:{}/s]*$/.test
. replace (/"[^"///n/r]* "|true|false|null|-?/d+ (?:/. /d*)? (?: [ee][+/-]?/d+)?/g, "]")
. replace (/(?: ^|:|,) (?:/ s*/[) +/g, "")) {
Try to use the native JSON parser
return window. JSON && windows. Json.parse?
Window. Json.parse (data):
(New Function ("return" + data) ();
} else {
Jquery.error ("Invalid JSON:" + data);
}
}
The core code of this method is:
Copy Code code as follows:
(New Function ("return" + data) ();
It uses the function () constructor. The JSON string is passed in as a function, the function is executed immediately after the definition, and this function returns the JSON object
I did a test that parsing the JSON string in this way is hundreds of times times faster than Eval parsing.
Copy Code code 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 the Firfox test results to spend 7234 milliseconds with eval parsing, and it was amazing to use the function method for 55 milliseconds.