jQuery: testing remote JSON data with a type check

The $.getJSON() method of jQuery provides an easy way to retrieve a JSON resource to be used in your documents. Unfortunately, this method doesn't provide an option to test whether the returned data has been fetched normally and is ready to be used. Instead of using $.ajax() as an alternative, you can enhance this method with a simple check on data to verify the correct parsing of the resource. Let's see how to implement this enhancement.

In its essence, the returned data takes the form of a JSON object. More specifically, it's an [object Object]. So you can run the following test:

var url = 'http://api.site.com/feed.json?callback';

$.getJSON(url, function(data)) {

  if(typeof data !== 'object') {
  
    // something went wrong
  
  }

});

This allows us to check if the returned JSON is actually what it's supposed to be.

Leave a Reply

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