Skip to content

Instantly share code, notes, and snippets.

@yairEO
Created January 5, 2023 09:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yairEO/9eaeeb7ab341fd8e91acb938b8a9f6af to your computer and use it in GitHub Desktop.
Save yairEO/9eaeeb7ab341fd8e91acb938b8a9f6af to your computer and use it in GitHub Desktop.
Safe javascript JSON.parse which never throws exceptions
JSON.parse = (JP => (...args) => {
try { return JP(...args) } catch{}
})(JSON.parse)
@yairEO
Copy link
Author

yairEO commented Jan 5, 2023

Test Cases:

console.log(JSON.parse());
console.log(JSON.parse(1));
console.log(JSON.parse(true));
console.log(JSON.parse(null));
console.log(JSON.parse('{"a": 1}'));
console.log(JSON.parse('[1, 2, 3]', (k,v) => typeof v === 'number' ? v * 2 : v);
console.log(JSON.parse('text'));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment