Home >Web Front-end >JS Tutorial >JSON.parse but without errors
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.
What we can do to fix it is simply introduce the method JSON.tryParse instead.
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; } };
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
This tutorial has helped us work with parsing JSON objects without having to worry about catchig errors every single time.
Happy developing!
The above is the detailed content of JSON.parse but without errors. For more information, please follow other related articles on the PHP Chinese website!