Using HTML5 localStorage To Store JSON

Options for persistent storage of complex JavaScript objects in HTML5

Our Persistent Storage Options

With HTML5 mobile apps we have threes candidates for presisent storage Web SQL Database, IndexedDB and Web Storage.

Of the three Web Storage has the widest support, particularly the localStorage aspect of specification. As localStorage is a key-value store, it's simplest of the three options. I classify simple as a strength.

The Truth about localStorage

Turns out localStorage likes to convert things to strings. Paste this code into the JavaScript console in Chrome to see for yourself.

Storing JSON, Functions And Arrays in localStorage

Luckily, we can store complex data in localStorage by leveraging the JSON object's stringify() and parse() functions. JSON support is quite good on mobile but if you need to add support use json2.js by Douglas Crockford.

Some things I find helpful when taking this approach:

  • Use a unqiue key to scope your data inside localStorage
  • Use load() and save() functions to abstract the use of localStorage.
  • As your data set increases in size, load() and save() become more expensive. You'll want a more granular load/save mechanism on larger data sets.

Apologies to IndexedDB and Web SQL

IndexedDB would be a great option (supports indexes, hierarchies and key-values) but it has very limited support. Web SQL Database is a traditional SQL approach to data with decent mobile support but the specification is at an impasse and mayb not be supported in the future.

Thanks for reading.

👋 Hey Sitecore Enthusiasts!

Sign up to our bi-weekly newsletter for a bite-sized curation of valuable insight from the Sitecore community.

What’s in it for you?

  • Stay up-to-date with the latest Sitecore news
  • New to Sitecore? Learn tips and tricks to help you navigate this powerful tool
  • Sitecore pro? Expand your skill set and discover troubleshooting tips
  • Browse open careers and opportunities
  • Get a chance to be featured in upcoming editions
  • Learn our secret handshake
  • And more!
Sitecore Snack a newsletter by Fishtank Consulting

Meet Dan Cruickshank

President | Sitecore MVP x 11

Dan is the founder of Fishtank. He's a multi-time Sitecore MVP and Coveo MVP award winner. Outside of technology, he is widely considered to be a top 3 father (routinely receiving "Father of the Year" accolades from his family) and past his prime on the basketball court.

Connect with Dan