el_pup_le
el_pup_le

Reputation: 12189

Handling errors for broken JSON

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

Answers (2)

Danil Speransky
Danil Speransky

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

Lix
Lix

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

Related Questions