
介绍
我们都曾遇到过这样的情况:我们只想调用 json.parse,并且如果我们尝试解析的值为 null 或未定义,则不会收到错误。
json.tryparse 来救援
我们可以做的就是简单地引入 json.tryparse 方法来解决这个问题。
执行
只需在应用程序开始时定义此函数并使其全局可用。
json.tryparse = function (value) {
try {
return json.parse(value);
} catch (error) {
return null;
}
};
用法
假设您想检索缓存的用户而不必尝试/cacth。方法如下:
const user = JSON.tryParse(localStorage.getItem("user"));
// returns "null" instead of throwing an error in case there is no entry
结论
本教程帮助我们解析 json 对象,而不必每次都担心出现问题。
祝您开发愉快!










