Reputation: 12189
If the element #the-json
is empty it will cause this error:
Uncaught SyntaxError: Unexpected end of input
For the following code:
myJSON = JSON.parse($("#the-json").attr('value'));
How should this error be handled so it doesn't stop the entire script working?
Upvotes: 7
Views: 3456
Reputation: 30473
Use try-catch statement:
try {
myJSON = JSON.parse($("#the-json").attr('value'));
} catch (e) {
// handle error
}
Or check before do something:
var myJSON = JSON.parse('{}'); // default value
if ($("#the-json").attr('value')) {
myJSON = JSON.parse($("#the-json").attr('value'));
}
Upvotes: 11
Reputation: 48006
Rather than catching errors when they happen - prevent errors from happening in the first place! Simply test the value attribute and if its empty - explicitly specify that it is. Then your JSON parser will not complain - it'll just create an empty object.
You can simply test for empty content and provide an empty object -
var data = $("#the-json").attr('value') == ''? '{}': $("#the-json").attr('value');
myJSON = JSON.parse(data);
if ($.isEmptyObject(myJSON)){
// there was no value
}
The {}
syntax implies an empty JavaScript object.
Upvotes: 3