Skip to content

Instantly share code, notes, and snippets.

@JonAbrams
Last active August 29, 2015 14:13
Show Gist options
  • Save JonAbrams/3b06be7f612c6e0cf6e0 to your computer and use it in GitHub Desktop.
Save JonAbrams/3b06be7f612c6e0cf6e0 to your computer and use it in GitHub Desktop.
Safe JSON.parse
(function () {
var ogJSONParse = JSON.parse;
JSON.parse = function (text, reviver) {
try {
return ogJSONParse(text, reviver);
} catch (err) {
console.error('Failed to parse: ', text);
console.error(err.stack);
return {};
}
};
})();
// Example usage:
console.log("Success: ", JSON.parse('{"item":true}'));
console.log("Fail: ", JSON.parse('{"item":true')); // outputs stack trace to stderr but continues
console.log("Still made it!");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment