我们都曾遇到过这样的情况:我们只想调用 json.parse,并且如果我们尝试解析的值为 null 或未定义,则不会收到错误。
我们可以做的就是简单地引入 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 对象,而不必每次都担心出现问题。
祝您开发愉快!
以上就是JSONparse 但没有错误的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号