更新时间:2023-02-25 19:48:34
每次您尝试为localStorage/sessionStorage保存/加载某些内容并且您知道它是一个json对象时,请始终根据情况对其进行字符串化/解析.
each time you try to save/load something for the localStorage/sessionStorage and you know it is a json object, always stringify/parse it depending on the case.
在这里,您的代码已修复,可以工作.
here you have your code fixed to work.
注意::我尝试创建一个代码段,但由于我们无法访问沙箱的sessionStorage,因此无法正常工作.
NOTE: I tried to create a snippet but it didn't work because we can not access to the sessionStorage of a sandbox.
注意2::始终检查要解析的数据,如果存储中不存在该记录,它将返回null
.
NOTE2: always check what data are you going to parse, if the record doesnt exist on the storage, it will return null
.
var data = {
"A43D": {
"FIRSTNAME": "Mike",
"EMAIL": "mjohns@gmail.com",
"LASTNAME": "Johns"
},
"4E83": {
"FIRSTNAME": "Steve",
"EMAIL": "scook@gmail.com",
"LASTNAME": "Cook"
}
}
//here we save the item in the sessionStorage.
sessionStorage.setItem("customersData", JSON.stringify(data));
//now we retrieve the object again, but in a string form.
var customersDataString = sessionStorage.getItem("customersData");
console.log(customersDataString);
//to get the object we have to parse it.
var customersData = JSON.parse(customersDataString);
console.log(customersData);