1

To parse JSON, I believe the best method is to use native JSON support in browsers.

I was looking for a good way to parse JSON in cases where native JSON support is not available.

When i looked at the code in https://github.com/douglascrockford/JSON-js/blob/master/json2.js, what i understood was it first checks whether the data is valid JSON using the regex:

if (/^[\],:{}\s]*$/.
test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, '')))

and then applies eval().

jQuery performs $.parseJSON() by 1st using the above regex to check if it's valid JSON and then applies:

return window.JSON && window.JSON.parse ?
    window.JSON.parse( data ) :
        (new Function("return " + data))();

if native JSON is available it uses that, otherwise it uses "new Function".

Nowhere else did i find about using function objects for parsing JSON. Which is a better method - using eval() or function object? Can you explain what exactly does (new Function("return " + data))(); perform?

4

2 回答 2

2

new Function("return "+data)在这种情况下与 eval 几乎相同。whereeval直接返回结果,(new Function("return "+data))()创建一个匿名函数并执行它。

我没有做过基准测试,但我认为new Function它比 eval 慢一点,因为首先创建一个函数,然后对代码进行评估。不要相信我的话,这只是我的大脑在想。

于 2010-08-26T12:00:30.400 回答
1

'new Function' 是执行 eval() 的一种更安全的方法,使用 eval,作用域链中的所有变量都可用于 evalled 代码,但对于 'new Function' 则不然,它确实使用了 eval(),但是无法访问作用域链中的变量。变量需要与传递的代码字符串连接。

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

基本上,创建了一个将“数据”转换为对象并返回它的函数,最后一个括号 () 立即调用该函数。由于没有创建对已创建函数的引用,因此垃圾收集器从对象堆栈中清除已创建函数。

于 2010-08-26T12:03:17.767 回答