Home  >  Article  >  Web Front-end  >  Examples of efficient methods for converting Json strings into JS objects_javascript skills

Examples of efficient methods for converting Json strings into JS objects_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:34:54813browse

Today I studied the JQuery source code and saw how to parse the JSON string like this:

Copy the code The 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 code The code is as follows:

(new Function("return " data))();

It uses the Function() constructor. The json string is passed in as function execution data, and the function is executed immediately after definition. At this time, this function will return a JSON object

I did a test and found that parsing JSON strings using this method is hundreds of times faster than using Eval

Copy code The 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 to test As a result, using eval to parse took 7234 milliseconds, while using the function method took 55 milliseconds, which is amazing.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn