HTML5 localStorage and JSON

localStorage stores data in the browser, making it available offline and/or persisting data between site visits. It stores data in a key/value format. Each site has its own partition of the localStorage resource, and keys for any given site must be unique.

You can store a value by simply typing:

window.localStorage.setItem(‘test’, ‘testing 1-2-3’);

Optionally, you can leave off the window prefix like so:

localStorage.setItem(‘hello’, ‘hello world’);

Retrieving information is also very simple, using the “getItem” method:

var myStoredVal = localStorage.getItem(‘hello’);

If you’re using JSON data and trying to serialize JavaScript objects, then you can use JSON.stringify to serialize your JSON:

var jsonObject = {
	a: 1,
	b: 42

var myJSON = JSON.stringify(jsonObject);
localStorage.setItem(‘firstJSON’, myJSON);

This will store your object in localStorage. When you’re ready to retrieve it and use it again, you can get it from localStorage then parse the JSON back into an object:

var firstJSON = localStorage.getItem(‘firstJSON’);
var backToObj = JSON.parse(firstJSON);

Now you have your JSON object back into a JavaScript object form!

If and when you’re ready to remove an item from local storage, simply call the .removeItem() method:


Optionally, if you want to erase everything your site has created in localStorage, you can call the .clear() method to delete everything: