localStorage存对象变成[object Object]怎么办?

上官润恺 阅读 28

在做用户设置保存时,把对象直接存到localStorage,结果查出来全是”[object Object]”,这是为啥啊?

比如我写了这样的代码:localStorage.setItem('userSettings', userSettings),然后控制台打印localStorage里的值就是”[object Object]”,但userSettings明明是包含theme和fontSize属性的对象…

试过用JSON.parse去取的时候报错:Uncaught SyntaxError: Unexpected token o in JSON at position 1,这中间是不是少了什么步骤?

我来解答 赞 7 收藏
二维码
手机扫码查看
2 条解答
长孙鑫平
localStorage只能存字符串,你得先用JSON.stringify转成字符串再存,取的时候用JSON.parse转回对象。试试看这样写:

localStorage.setItem('userSettings', JSON.stringify(userSettings));
let settings = JSON.parse(localStorage.getItem('userSettings'));


别直接塞对象进去,不然调用的是对象的toString方法,肯定变成[object Object]。我几年前也踩过这个坑,烦得很。
点赞
2026-02-18 03:02
西门锡丹
最简单的办法是存之前用 JSON.stringify 转成字符串,读的时候用 JSON.parse 转回来。

localStorage.setItem('userSettings', JSON.stringify(userSettings));
const saved = JSON.parse(localStorage.getItem('userSettings'));


不然 localStorage 只能存字符串,对象直接转字符串就是 "[object Object]"。
点赞 3
2026-02-11 01:01