Simple wrapper around JSON global that adds graceful error handling via try/catch. 😋
module.exports = (function(){
var parse = JSON.parse;
return {
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;
}
}
};
})();
JSON = require('json');
console.log(JSON.parse("{oops}")||{event:''}); // assignment for ensuring consistency
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"}