Introduction
We've all been in the situation where we simply want to call JSON.parse and not get an error if the value we're trying to parse is null or undefined.
JSON.tryParse to the rescue
What we can do to fix it is simply introduce the method JSON.tryParse
instead.
Implementation
Simply define this function in your application at the beginning and make it globally available.
JSON.tryParse = function (value) {
try {
return JSON.parse(value);
} catch (error) {
return null;
}
};
Usage
Let's say you want to retreive a cached user without having to try/cacth. This is how:
const user = JSON.tryParse(localStorage.getItem("user"));
// returns "null" instead of throwing an error in case there is no entry
Conclusion
This tutorial has helped us work with parsing JSON objects without having to worry about catchig errors every single time.
Happy developing!