日期:2014-05-16 浏览次数:20285 次
var str = '{ "key": "key" ';//str = '{ "x": "Hello, World!", "y": [1, 2, 3] }'; for(var i=0; i<10000; i++){ str = str + ',' + '"key' + i + '" : "key' + i + '"'; } str = str + '}';
var jsonObject = eval('(' + str + ')');
var jsonObject = (new Function("return " + str))();
var jsonObject = JSON.parse(str);
总结:eval与new Function方式都不安全,其中new Function比eval高效! JSON方式相对上面两种方式来说,更安全,更高效!但是在一些版本低的浏览器中不兼容!
//jQuery源码中的parseJSON方法 function parseJSON(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))(); } return null; }