Skip to content

Instantly share code, notes, and snippets.

@topherPedersen
Created September 23, 2021 23:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save topherPedersen/90e4b304b7217eee3b498d59292d3674 to your computer and use it in GitHub Desktop.
Save topherPedersen/90e4b304b7217eee3b498d59292d3674 to your computer and use it in GitHub Desktop.
TypeScript JSON.parse undefined
const json = '{"foo": { "bar": { "baz": {"a": 1, "b": 2, "c": 3}}}}';
const parsedJSON = JSON.parse(json);
/*
* DANGER! This line will run, but is not fail-safe, could crash if foo, bar,
* baz or a is missing or undefined
*/
console.log(parsedJSON.foo.bar.baz.a);
// This line will fail gracefully foo, bar, baz, or b is missing/undefined
console.log(parsedJSON?.foo?.bar?.baz?.b);
// This line fails gracefully
console.log(parsedJSON?.foo?.bar?.baz?.z);
// DANGER! DANGER! This line will crash
// console.log(parsedJSON?.foo?.bar?.baz?.x.y.z);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment