Example of an efficient method for converting a Json string to a JS object

Source: Internet
Author: User
Tags date1

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 codeCode: 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.

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.