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');
}
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']);
});
The most common way to handle JSON parse error is using try-catch block. If the JSON string is valid, it will return a JavaScript object. If the JSON string is invalid, it will throw a SyntaxError.
parseJSON( json )Returns: String or Number or Object or Array or Booleanversion deprecated: 3.0. Description: Takes a well-formed JSON string and returns the resulting JavaScript value.
JSON. parse() parses a string as JSON. This string has to be valid JSON and will throw this error if incorrect syntax was encountered.
The "SyntaxError: JSON. parse: unexpected character" error occurs when passing a value that is not a valid JSON string to the JSON. parse method, e.g. a native JavaScript object. To solve the error, make sure to only pass valid JSON strings to the JSON.
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With