Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.parseJSON - Chrome and Safari automatically parsing JSON

Tags:

json

jquery

The following function results in the response variable being null in Chrome and Safari but not Firefox.

function updatePage(response){ // This argument differs by browser

    response = jQuery.parseJSON(response);

    for(var i=0; i<response.length; i++){
        // conduct magic
    };

};

Error:

Uncaught TypeError: Cannot read property 'length' of null

This is because feeding jQuery.parseJSON() anything but a JSON string returns null. It seems Chrome and Safari automatically parse JSON without explicitly being requested. If I test the "response" argument before trying to parse it with jQuery, it's already a JSON object in both Chrome and Safari. However, in Firefox it's still a string.

The only solution I've come up with to handle this across browsers is to determine if "response" has already been parsed by checking its constructor:

function updatePage(response){

    if(response.constructor === String){
        response = jQuery.parseJSON(response);
    };

    for(var i=0; i<response.length; i++){
        // conduct magic
    };

};

Am I missing something or is this the only way to handle this currently? Seems like jQuery.parseJSON would detect the user-agent and just return the argument as-is in the case of Chrome/Safari.

Pertinent information

  • This is jQuery 1.6.1
  • The response Content-Type from the server is application/json
  • The response argument is originating from your standard jQuery AJAX call:

$.ajax({
    url: API_URL + queryString + '&limit=' + limit,
    type: 'GET',
    cache: false,
    context: document.body,
    success: updatePage,
    error: function(err){
        console.log('ERROR: ' + err);
    }
});
like image 897
Chris Cummings Avatar asked Jun 21 '11 05:06

Chris Cummings


1 Answers

It's not Chrome or Safari, it's jQuery that does the parsing if it sees the appropriate Content-Type on the response. (Update: And the Content-Type you've added to the question is correct.) I can't immediately see why it wouldn't be doing it on Firefox.

You can force it to always do the parsing by adding dataType: 'json' to your call, details in the jQuery.ajax docs. Then you wouldn't call parseJSON at all, response would already be the deserialized object.

like image 88
T.J. Crowder Avatar answered Oct 14 '22 04:10

T.J. Crowder