Skip to content

Instantly share code, notes, and snippets.

@tzechienchu
Forked from geuis/json.js
Created August 10, 2016 01:59
Show Gist options
  • Save tzechienchu/08fba2f2737d0033cc5bdea6e1531564 to your computer and use it in GitHub Desktop.
Save tzechienchu/08fba2f2737d0033cc5bdea6e1531564 to your computer and use it in GitHub Desktop.
Better error handling for JSON.parse (javascript)
(function(){
var parse = JSON.parse;
JSON = {
stringify: JSON.stringify,
validate: function(str){
try{
parse(str);
return true;
}catch(err){
return err;
}
},
parse: function(str){
try{
return parse(str);
}catch(err){
return undefined;
}
}
}
})();
console.log( JSON.validate('{"foo":"bar"}') ); //true
console.log( JSON.validate('{foo:"bar"}') ); //Error message: [SyntaxError: Unexpected token f]
console.log( JSON.parse('{"foo":"bar"}') ); // js object, { foo: 'bar' }
console.log( JSON.parse('{foo:"bar"}') ); //undefined
console.log( JSON.stringify({foo:"bar"}) ); //{"foo":"bar"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment