In the following code, if the JSON I'm trying to read has a slight syntax error somewhere, then it just doesn't say anything, I cannot find the error shown in Chrome or Firefox that tells me that it cannot parse the JSON field . Even this try / catch does not work.
How can I get my code to do something specific if 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'); }
Adding
Thanks to @sagi for working, here is the code that catches syntax problems 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']); });
source share