在localStorage中设置的字符串作为对象获取
我已经将JSON.stringified对象保存在localStorage中,但是将它们作为无法解析的对象("[object Object]")进行检索.
I've JSON.stringified objects to save in localStorage, but they're retrieved as objects ( "[object Object]" ) that can't be parsed.
场景:
我要做的第一件事是
localStorage.clear();
我创建了3个对象作为默认加载到localStorage中.每个对象都是JSON.stringified并使用其自己的密钥保存在localStorage中.然后,我使用一个for循环和localStorage.key(i)来获取密钥并检索对象(字符串).
I've created 3 objects to load into localStorage as a default. Each object is JSON.stringified and saved with it's own key in localStorage. Then, I use a for loop and localStorage.key(i) to get the key and retrieve the objects (strings).
if (localStorage.length === 0) {
// make 3 objects
console.log(typeof c); // logs "string"
localStorage.setItem("_fruit", a);
localStorage.setItem("_veggie", b);
localStorage.setItem("_protein", c);
var test = localStorage.key(0);
test = localStorage.getItem(test);
console.log(test); // logs stringified JSON
}
到目前为止,一切都很好.在if语句之外,我有:
So far so good. Outside the if statement I have:
var test = localStorage.key(0);
console.log(test); // logs correct key
test = localStorage.getItem(test);
console.log(test); // logs string of object
test = JSON.parse(test);
console.log(test); // logs object correctly
这也输出到DOM罚款.但是一旦我注释掉
And this also outputs to the DOM fine. But as soon as I comment out
// localStorage.clear();
要测试从本地存储的检索,我遇到了这个问题:
To test the retrieval from local storage, I have this problem:
var test = localStorage.key(0);
console.log(test); // logs correct key
test = localStorage.getItem(test);
console.log(test); // logs "[object Object]"
test = JSON.parse(test); <------ logs Unexpected token o in JSON at position 1
console.log(test); // code stops above
我知道不能保证索引本地存储的顺序,这很好.如果可以,请使用React.
I'm aware there's no guarantee about the order of indexing local storage and that's fine. Using React if that makes a difference.
在存储对象之前,您需要对它进行字符串化:
You need to stringify an object before storing it:
localStorage.setItem('key', JSON.stringify(obj));
然后,在检索它时,您只需
Then, when retrieving it, you just do
JSON.parse(localStorage.getItem('key'));
之所以这样做是因为所有内容都存储为字符串,因此它调用.toString()方法,该方法对于对象返回[object Object]
The reason for this is that everything is stored as a string, so it calls the .toString() method, which for objects returns [object Object]
编辑 我注意到您说您确实对对象进行了字符串化.我猜想那将取决于对象的格式,但是我没有遇到任何不事先清除存储空间的问题.
EDIT I noticed you said you did stringify the objects. I guess it would depend the format of the object then, but I haven't encountered any issue with not clearing storage beforehand.