Skip to content

Instantly share code, notes, and snippets.

@geuis
Created November 15, 2011 16:01
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save geuis/1367429 to your computer and use it in GitHub Desktop.
Save geuis/1367429 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