如何通过localStorage获取JSON数据?解决JSON.parse解析null报错问题
解决localStorage获取null导致JSON.parse报错的问题
问题原因
当localStorage.getItem('userSettings')返回null时(比如该键从未被存储、已被手动删除,或是浏览器清除了存储数据),直接把null传给JSON.parse()会抛出错误——因为JSON.parse()要求参数必须是有效的JSON字符串,而null是一个原始值,并非字符串格式。
修复方案
方案1:先判断值是否存在再解析
先检查获取到的存储值是否有效,无效则用预设的默认设置对象初始化:
let userSettings; const storedSettings = localStorage.getItem('userSettings'); if (storedSettings) { userSettings = JSON.parse(storedSettings); } else { // 根据需求定义默认设置 userSettings = { theme: 'light', notifications: true }; }
方案2:用短路运算符简化代码
利用逻辑或(||)提供默认的JSON字符串,确保JSON.parse()始终能拿到有效参数:
const userSettings = JSON.parse(localStorage.getItem('userSettings') || '{"theme":"light","notifications":true}');
方案3:ES2020+ 简洁写法(可选链+空值合并)
如果项目环境支持ES2020及以上语法,可用更简洁的空值合并运算符:
const storedSettings = localStorage.getItem('userSettings'); const userSettings = JSON.parse(storedSettings ?? '{"theme":"light","notifications":true}');
额外排查建议
- 打开浏览器开发者工具(F12)的Application标签,查看
localStorage列表中是否存在userSettings键,确认数据是否真的未存储或已丢失。 - 检查存储设置的代码,确保调用
localStorage.setItem('userSettings', JSON.stringify(yourSettingsObject))时,传入的是有效的对象,没有误传null或undefined。
内容的提问来源于stack exchange,提问作者Abygail Caffrey
相关产品推荐
相关产品推荐

