How can I catch JSON parsing errors in JQuery?

Edward Tanguay picture Edward Tanguay · May 23, 2013 · Viewed 10.6k times · Source

In the following code, if the JSON I am trying to read in has a slight syntax error somewhere, then it simply doesn't say anything, I can't find any error shown in Chrome or Firefox which is telling me that it cannot parse the JSON field. Even this try/catch doesn't work.

How can I get my code to do something specific if the JSON cannot be parsed?

function init() {
    elemFront = $('div.flashcard div.bodyFront');
    elemBack = $('div.flashcard div.bodyBack');
    console.log('before');
    try {
        console.log('inside try');
        $.getJSON('data.txt', function(jsonResult) {
            console.log(jsonResult);
        });
    } 
    catch(err) {
        console.log('error');
    }
    console.log('after');
}

Addendum

Thanks @sagi, that worked, here's the code that catches syntax issues with JSON data:

$.get('data.txt', {}, function(data, response){
    var jsonResult;
    try {
        jsonResult = JSON.parse(data);
    }
    catch (e) {
        $('div.header').html('<span style="color:red">cannot load data because: "'+e+'"</span>');
    };
    $('div.bodyFront').html(jsonResult['one']);
});

Answer

Sagish picture Sagish · May 23, 2013

if you are unsure of the response, you shouldn't use $.getJSON, instead you might want to do something like this

$.get('...', {}, function(data, response){
  var jsonResult;
  try {
    jsonResult = JSON.parse(data);
  }
  catch (e) {
    console.log("error: "+e);
  };
  // the rest of your code
});