JSON

jQuery.parseJSON vs JSON.parse

字号+ 作者:H5之家 来源:H5之家 2016-12-11 16:00 我要评论( )

jQuery.parseJSON vs JSON.parse,JSON.parse()andjQuery.parseJSON(),bothareusedtoparseaJSONstringandreturnsresultingjavascriptvalueorobjectdescribedbythe

JSON.parse() and jQuery.parseJSON(), both are used to parse a JSON string and returns resulting javascript value or object described by the string. jQuery.parseJSON() is available only when jQuery library is used where JSON.parse() is JavaScript’s standard built-in JSON object method. So the question is if jQuery library is used, then which one should be used or both gives same performance and result?

Well, the answer is that both are equal. As you know, jQuery’s library is written on top of JavaScript. So jQuery.parseJSON() makes use of JSON.parse() internally. Here is the code of jQuery.parseJSON() method from jQuery 1.9.1 library. As you can see, it first checks if JSON.parse is supported or not. If supported, then it makes use of JSON.parse only. Otherwise, it tries to evaluate string data with new Function.

// 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 if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } } } jQuery.error( "Invalid JSON: " + data ); }

This was done as JSON.parse is natively available on some browsers, and jQuery is browser independent. So if JSON.parse is not available, then it falls back to jQuery implementation.

JSON.parse was not supported in old browsers like IE 7 and Safari 3, but over the period of time, browsers have also evolved. And now most of the browsers support JSON.parse. Therefore, the implementation of jQuery.parseJSON() is also changed after jQuery 2.0 release. Here is the code of new implementation from jQuery 2.2.4 library:

 

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

相关文章
  • JS中JSON对象和String之间的互转及处理技巧

    JS中JSON对象和String之间的互转及处理技巧

    2016-05-30 17:02

  • JS学习笔记9_JSON

    JS学习笔记9_JSON

    2015-11-21 09:00

  • Shunter - a Node.js application built to read JSON and trans

    Shunter - a Node.js application built to read JSON and trans

    2015-11-17 11:39

  • json学习小记

    json学习小记

    2015-11-10 11:25

网友点评