Reputation: 1462
I have a JSON array in Jquery that I am trying to save to localStorage for later use, but for some reason, whenever I try and save it, it comes up with an error that the object is not defined. Here is my current code:
localStorage.setItem("Jsonobject", JSON.stringify(json));
var jsonobject = JSON.parse(localStorage.getItem(Jsonobject));
The error specifically states "Jsonobject is not defined" even though I just defined it in the line above. I have tried "Jsonobject" with single and double quotes and they both come up with the same error. I have followed the instructions on this page, https://www.smashingmagazine.com/2010/10/local-storage-and-how-to-use-it/, but it doesn't seem to be working for some reason.
Upvotes: 0
Views: 282
Reputation: 336
The error happens because you do not put "Jsonobject" in quotation marks then the interpreter of JS assumes that you are referring to a variable and since it does not exist the variable, the interpreter tells you that it is not defined
Error:
localStorage.getItem(Jsonobject)
Correct:
localStorage.getItem('Jsonobject')
or
var itemKey = 'Jsonobject';
// Setting value
localStorage.setItem(itemKey, JSON.stringify(json));
// Getting value
var json = JSON.parse(localStorage.getItem(itemKey));
Upvotes: 3