【问题标题】:How can you load a json file into localstorage?如何将 json 文件加载到本地存储中?
【发布时间】:2022-01-21 06:10:53
【问题描述】:

是否可以将 JSON 文件的内容加载到本地存储中? 就我而言,我有一个 JSON 文件,它是一个对象数组。我希望在启动应用程序时将 JSON 文件加载到本地存储中,然后我想访问本地存储中的数组以显示在 DOM 中。

这是我发现似乎有效的方法。我是新手,所以我不完全了解这是否是最佳解决方案。

var catObjArray = require ('./data/cats.json');
var newObject = JSON.stringify(catObjArray)
console.log(newObject)

// Put the cat array of objects into local storage
localStorage.setItem('catObject', JSON.stringify(catObjArray));

// Retrieve the cat array of objects from local storage
var catsFromLocalStorage = localStorage.getItem('catObject');

console.log('retrievedCatObjArray: ', JSON.parse(catsFromLocalStorage));

【问题讨论】:

  • 请展示你到目前为止所做的事情。您现在如何开始申请
  • 添加了我目前所拥有的。

标签: json local-storage


【解决方案1】:

一切都很好,但您不需要字符串化和解析数据来使用存储

<script type="text/javascript">
            
 $.getJSON('./data/cats.json', function(json) {
 

// Put the cat array of objects into local storage
localStorage.setItem('catObject', json);

createHtml();

   });

function createHtml()
{
// Retrieve the cat array of objects from local storage
var catsFromLocalStorage = localStorage.getItem('catObject');

  ...your code

};

</script>

【讨论】:

  • 不客气!如果有帮助,请不要忘记接受答案。您可以通过单击我的答案旁边的复选标记来完成。
猜你喜欢
  • 2017-03-03
  • 1970-01-01
  • 2013-01-07
  • 2022-01-13
  • 1970-01-01
  • 2017-05-08
  • 2012-06-01
  • 2016-03-13
相关资源
最近更新 更多