localstorage json行如何访问每一行及其各个元素
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了localstorage json行如何访问每一行及其各个元素相关的知识,希望对你有一定的参考价值。
How can I access to a localStorage item?
在这种情况下,我在localStorage中有以下对象数组:
[
{
"id1":"my_id",
"title":"My_title",
"subject":"subject1"
},
{
"id2":"my_id",
"title":"My_title2",
"subject":"subject2"
},
{
"id3":"my_id",
"title":"My_title3",
"subject":"subject3"
},
{
"id4":"my_id",
"title":"My_title4",
"subject":"subject4"
}
]
请任何人都可以帮助我。我想从localStorage数据访问它。
答案
您可以使用Storage界面的localStorage
方法访问getItem数据。
// just change [my-local-storage-data-key] string for your actual data key on localStorage
const data = localStorage.getItem("[my-local-storage-data-key]");
const jsonData = JSON.parse(data);
// -> jsonData holds your array of objects
了解更多关于localStorage的信息。
// copy the following to your browser console and check outputs
// trying to run this code snippet will fail because the document is sandboxed and lacks the "allow-same-origin' flag."
const myDataArray = [
{
"id1":"my_id",
"title":"My_title",
"subject":"subject1"
},
{
"id2":"my_id",
"title":"My_title2",
"subject":"subject2"
},
{
"id3":"my_id",
"title":"My_title3",
"subject":"subject3"
},
{
"id4":"my_id",
"title":"My_title4",
"subject":"subject4"
}
];
// saving to localStorage with `rows` as key
const serializedData = JSON.stringify(myDataArray);
localStorage.setItem('rows', serializedData);
// retrieving data from localStorage `rows` key
const data = localStorage.getItem('rows');
const jsonData = JSON.parse(data);
console.log('jsonData from localStorage:', jsonData);
// -> jsonData from localStorage: (4) [{…}, {…}, {…}, {…}]
console.log('jsonData[0]:', jsonData[0]);
// -> jsonData[0]: {id1: "my_id", title: "My_title", subject: "subject1"}
// remove localStorage item `rows`
localStorage.removeItem('rows');
以上是关于localstorage json行如何访问每一行及其各个元素的主要内容,如果未能解决你的问题,请参考以下文章
如何将 pandas DataFrame 行保存为 JSON 字符串?
将数据从 json 存储到 localStorage 浏览器