How can I catch JSON errors in jQuery?

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']); }); 
+6
source share
1 answer

if you are not sure about the answer, you should not use $ .getJSON, instead you can 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 }); 
+10
source

Source: https://habr.com/ru/post/945699/


All Articles