Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 248
Question Overflow Avatar asked Apr 28 '12 09:04

Question Overflow


People also ask

What is JSON parse jQuery?

The jQuery parseJSON() method takes a JSON string and returns a JavaScript object. The specified JSON string must follow the strict JSON format. Passing an incorrect string will cause a JS exception. Some of the examples of malformed JSON strings that can cause an exception on passing are given as follows -

What is the difference between JSON parse and JSON Stringify?

The JSON. parse() function is used to convert a string into a JavaScript object while the JSON. stringify() function is used to convert a JavaScript object into a string.

What is parse JSON?

JSON parsing is the process of converting a JSON object in text format to a Javascript object that can be used inside a program. In Javascript, the standard way to do this is by using the method JSON. parse() , as the Javascript standard specifies.


2 Answers

Here is an extract from 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 ); }, 

As you can see, jQuery will use the native JSON.parse method if it is available, and otherwise it will try to evaluate the data with new Function, which is kind of like eval.

So yes, you should definitely use jQuery.parseJSON.

like image 177
dfsq Avatar answered Sep 19 '22 07:09

dfsq


According to jQuery

Where the browser provides a native implementation of JSON.parse, jQuery uses it to parse the string.

thus it means that jQuery provides a JSON parser if no native implementation exists on the browser. here's a comparison chart of browsers that have (and don't have) JSON functionality

like image 33
Joseph Avatar answered Sep 20 '22 07:09

Joseph