Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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