Is it possible to load the contents of a JSON file into local storage? In my case, I have a JSON file that is an array of objects. I would like to have the JSON file load into local storage when I start up an app, then I would like to access the array in local storage to display in the DOM.
Here is what I have found that seems to work. I am new to this so I don't fully understand if this is the optimal solution.
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));
CodePudding user response:
everything is fine, but you don' t need stringify and parse data to use storage
<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>