-
-
Save tzechienchu/08fba2f2737d0033cc5bdea6e1531564 to your computer and use it in GitHub Desktop.
Better error handling for JSON.parse (javascript)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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