An efficient method instance for converting JSON strings to JS objects _javascript tips

Source: Internet
Author: User
Tags date1

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.

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.