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 字符串?

如何将源文件名添加到 Spark 中的每一行?

将数据从 json 存储到 localStorage 浏览器

如何在 Scala/Spark 中为数据框中的每一行编写一个 Json 文件并重命名文件

反应如何访问 JSON 文件中的对象