Json字符串转换为JS对象的高效方法实例_javascript技巧
May 16, 2016 pm 05:34 PM今天学习JQuery源码看到一下方法,原来还可以这样解析JSON字符串:
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 );
}
}
这个方法核心的代码就是:
(new Function("return " + data))();
它使用了Function()构造函数。讲json字符串作为函数执行数据传入,定义后立即执行该函数,此时这个函数会返回JSON对象
我做了一个测试,用这个方法解析JSON字符串的效率要比用Eval解析快好几百倍
var jsonStr ="{";
for(var i=0;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);
我用firfox测试结果,用eval解析花费了7234毫秒,而用函数这种方法,用了55毫秒,太神奇了.

Article chaud

Outils chauds Tags

Article chaud

Tags d'article chaud

Bloc-notes++7.3.1
Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise
Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1
Puissant environnement de développement intégré PHP

Dreamweaver CS6
Outils de développement Web visuel

SublimeText3 version Mac
Logiciel d'édition de code au niveau de Dieu (SublimeText3)

Sujets chauds

Conseils d'optimisation des performances pour la conversion de tableaux PHP en JSON

Explication détaillée de la méthode de conversion du type int en chaîne en PHP

Comment les annotations de la bibliothèque Jackson contrôlent-elles la sérialisation et la désérialisation JSON ?

Comment déterminer si une chaîne Golang se termine par un caractère spécifié

Comment vérifier si une chaîne commence par un caractère spécifique en Golang ?

Comment répéter une chaîne dans le didacticiel de chaîne répétitive python_python

Manipulation de chaînes PHP : un moyen pratique de supprimer efficacement les espaces

Techniques PHP pour supprimer les deux derniers caractères d'une chaîne
