json.parse不能直接解析localstorage中的值,因localstorage只存字符串,必须先用json.stringify序列化再用json.parse反序列化,且需用try...catch容错处理解析失败情况。

JSON.parse 不能直接“利用 HTML”来反序列化,它是一个 JavaScript 函数,必须在 JS 执行环境中调用。浏览器中 localStorage 只支持字符串存储,所以存进去的 JSON 对象必须先 JSON.stringify,取出来时再用 JSON.parse —— 这是唯一安全、标准的做法。
为什么不能直接用 localStorage.getItem 返回的对象?
localStorage 的所有值都是字符串类型,哪怕你存的是 { "name": "Alice" },底层也只存为字符串。如果跳过 JSON.parse 直接当对象用,会得到 undefined 或报错(比如调用 .name 时提示“Cannot read property 'name' of null”)。
常见错误现象:
- 控制台报错:
TypeError: Cannot read property 'xxx' of null - 返回值是字符串,但代码当作对象解构:
const { name } = localStorage.getItem('user')→ 报错 - 没加
try...catch,遇到损坏的 JSON 字符串(如手动编辑过 localStorage)直接中断脚本
正确写法:带容错的 JSON.parse 封装
不要裸写 JSON.parse(localStorage.getItem('key'))。实际项目中必须处理解析失败的情况。
推荐做法:
- 用
try...catch包裹,避免崩溃 - 检查返回值是否为
null或空字符串 - 返回默认值(如
{}或null),而非抛异常
示例:
function getJsonFromStorage(key) {
const str = localStorage.getItem(key);
if (!str) return null;
try {
return JSON.parse(str);
} catch (e) {
console.warn(`Failed to parse JSON from localStorage key "${key}":`, e);
return null;
}
}
const user = getJsonFromStorage('user'); // 安全获取
if (user && user.name) {
console.log(user.name);
}
存的时候别漏掉 JSON.stringify
反序列化出问题,八成是因为序列化时就没做对。常见疏漏:
- 直接
localStorage.setItem('user', { name: 'Alice' })→ 实际存入的是[object Object] - 存了
undefined或function,JSON.stringify会静默丢弃这些字段(undefined键被忽略,函数值变null) - 对象含循环引用,
JSON.stringify报TypeError: Converting circular structure to JSON
务必确认写入前已正确序列化:
const user = { name: 'Alice', age: 30 };
localStorage.setItem('user', JSON.stringify(user)); // ✅
注意兼容性和边界情况
JSON.parse 本身兼容所有现代浏览器,但容易被忽略的点有:
-
localStorage容量限制(通常 5–10MB),超限时setItem抛QuotaExceededError,不会影响parse,但会导致后续读不到新数据 - 跨域 iframe 或私密模式下,
localStorage可能被禁用,getItem返回null,此时JSON.parse(null)会变成JSON.parse("null")→ 返回原始null,不是报错,但逻辑可能误判 - 服务端渲染(SSR)环境没有
localStorage,需加typeof window !== 'undefined'判断
最常被跳过的一步:没验证 localStorage.getItem 是否真返回了字符串——它可能返回 null,而 JSON.parse(null) 是合法的(返回 JS 值 null),不是你想的“解析失败”。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











