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.

Meet Dan Cruickshank


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