jQuery.parseJSON vs JSON.parse

jQuery.parseJSON and JSON.parse are two functions that perform the same task. If the jQuery library is already loaded, would using jQuery.parseJSON be better than using JSON.parse, in terms of performance?

If yes, why? If no, why not?

38534 次浏览

根据 jQuery

在浏览器提供 JSON.parse 的本机实现的地方,jQuery 使用它来解析字符串。

因此,这意味着如果浏览器上不存在本机实现,jQuery 将提供 JSON 解析器。具有(和不具有) JSON 功能的浏览器的 这是对比表

我不知道性能如何,但是使用 jQuery 方法肯定更安全,因为一些浏览器,比如 ie7或更低版本,可能本身没有任何 JSON 功能。
这完全是兼容性问题,就像在迭代中使用 jQuery 的 each 方法而不是数组的本机 forEach方法一样。

下面是一段摘录 来自 jQuery 1.9.1:

parseJSON: function( data ) {
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}


if ( data === null ) {
return data;
}


if ( typeof data === "string" ) {


// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );


if ( data ) {
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {


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


jQuery.error( "Invalid JSON: " + data );
},

如您所见,如果可用,jQuery 将使用本机 JSON.parse方法,否则它将尝试使用 new Function计算数据,这有点像 eval

所以,是的,你绝对应该使用 jQuery.parseJSON

Parse ()在某些浏览器上是本机可用的,而在其他浏览器上是不可用的,所以使用库更安全。正如其他受访者所指出的,JQuery 实现工作得很好。还有 道格拉斯·克罗克福特的 JSON 库,它使用本机实现(如果可用的话)。

The JSON library has the advantage that it has a method to turn a JavaScript object into a JSON string, which is missing from jQuery at the moment..

谈到 表演最新消息的答案是 JSON.parse

本机 JSON 对象现在是 每一个浏览器中的 支持,所以选择 JSON.parse。您可以在这里看到支持表: http://caniuse.com/#feat=json

您还可以在 GitHub: https://github.com/jquery/jquery/search?utf8=%E2%9C%93&q=parseJSON上的 JQuery 存储库中搜索这个别名外观

此外,jQuery.parseJson在3.0 + 版本上是 不赞成,这里的其他答案也提到了这一点。

如果您想为非常老的浏览器提供支持(通常是 不推荐) ,那么只能使用 jQuery 的版本,如果您是旧的 JQuery 版本 + 。

如果您使用的是 jQuery 版本3(2016年发布) ,那么您应该使用 JSON.parse(),因为 jQuery.parseJSON() 已经被否决了

从 jQuery 3.0开始,$. parseJSON 不被推荐使用。

JQuery 在内部使用 JSON.parse来解析 JSON 文件,所以在大多数情况下没有任何区别。

但是一些老的浏览器并不支持 functionality.in JSON.parse,这种情况下使用 jQuery.parseJSON是有益的,因为 jQuery 可以使用自己的功能来处理 JSON。

注意:

在 jQuery 3.0中不推荐使用 jQuery.parseJSON,因此请使用本机 JSON.parse方法。