jQuery unveiled: the parseJSON() method

The jQuery's parseJSON() method is used internally by the library to handle JSON data. It is as follows:

parseJSON: function( 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))();

  } else {
   jQuery.error( "Invalid JSON: " + data );
  }
 },
  1. checks if the passed data is a string or not; if not, returns null
  2. removes all unnecessary white-space by calling its trim() method, because Internet Explorer is not able to handle it
  3. uses a regular expression to checks if the data passed in is in the correct format (specified at json.org
  4. tries to use the native parse function implemented on some browsers (except Internet Explorer); if that function is not present, creates an anonymous function and passes the incoming data to it
  5. if something goes wrong, returns an error by sending it to the browser console.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.