Skip to content

Instantly share code, notes, and snippets.

@kostiantyn-petlia
Last active December 19, 2018 16:45
Show Gist options
  • Save kostiantyn-petlia/8f87071158a49d19d8e77c5e5c4c4459 to your computer and use it in GitHub Desktop.
Save kostiantyn-petlia/8f87071158a49d19d8e77c5e5c4c4459 to your computer and use it in GitHub Desktop.
Save JSON parsing
// Save JSON parsing
function tryParseJSON(jsonString) {
try {
var o = JSON.parse(jsonString);
// Handle non-exception-throwing cases:
// Neither JSON.parse(false) or JSON.parse(1234) throw errors, hence the type-checking,
// but... JSON.parse(null) returns null, and typeof null === "object",
// so we must check for that, too. Thankfully, null is falsey, so this suffices:
if (o && typeof o === "object") {
return o;
}
}
catch (e) {
console.log('tryParseJSON() catch!');
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment