Note that there are some explanatory texts on larger screens.

plurals
  1. POjQuery.parseJSON - Chrome and Safari automatically parsing JSON
    text
    copied!<p>The following function results in the response variable being null in Chrome and Safari but not Firefox.</p> <pre><code>function updatePage(response){ // This argument differs by browser response = jQuery.parseJSON(response); for(var i=0; i&lt;response.length; i++){ // conduct magic }; }; </code></pre> <p>Error:</p> <pre><code>Uncaught TypeError: Cannot read property 'length' of null </code></pre> <p>This is because feeding jQuery.parseJSON() anything but a JSON <strong>string</strong> 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.</p> <p>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:</p> <pre><code>function updatePage(response){ if(response.constructor === String){ response = jQuery.parseJSON(response); }; for(var i=0; i&lt;response.length; i++){ // conduct magic }; }; </code></pre> <p>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.</p> <p><strong>Pertinent information</strong></p> <ul> <li>This is jQuery 1.6.1 </li> <li>The response Content-Type from the server is application/json </li> <li>The response argument is originating from your standard jQuery AJAX call:</li> </ul> <hr> <pre><code>$.ajax({ url: API_URL + queryString + '&amp;limit=' + limit, type: 'GET', cache: false, context: document.body, success: updatePage, error: function(err){ console.log('ERROR: ' + err); } }); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload