HTML 5 Object Persistance

Uncategorized on December 27th, 2009 3 Comments

The natural progression from local / session storage is database storage. HTML 5 allows you to persist data in a SQLite style database on the client. This, however, would require a working knowledge of SQL and relational databases.

Rather than bogging you down with all of that this tutorial will show you a simple way to persist complex object orientated data using just the local storage tips we discussed before and a little JSON magic.

What we’ll do to persist an object is simple:

  1. Create a JS object
  2. Turn it in to a string
  3. Record that string in a key value pair

To load the object we:

  1. Load that string using a key
  2. Turn that string back in to an object

Object persistance can come in handy in a number of use cases, for example, preserving an application state between visits. For example, a partially completed form.

For the first step it’s as simple as creating a javascript object. For good measure we’ll set some data as well.

var user = new Object();
user.name = "Bradley Stacey";
user.site="http://openbit.co.uk";
user.quote = "\"A child miseducated is a child lost.\" - John Fitzgerald Kennedy";

Next we produce a string that represents that object. We call this JSON (javascript object notation).

JSON.stringify(user);

This creates the following string:

{"name":"Bradley Stacey","site":"http://openbit.co.uk/","quote":"\"A child miseducated is a child lost.\" - John Fitzgerald Kennedy"}

To create the string and record it in local storage we call the following:

localStorage.setItem("user", JSON.stringify(user));

Now our data is persisted, as outlined in the previous article.
To read this data as a string we can simply call the following:

localStorage.getItem("user");

This, however, would be more useful if we could restore the object to its previous state. We can then use it in any of the functions we’ve created.
We can achieve this by calling the following:

var user = JSON.parse(localStorage.getItem("user"));

This uses the javascript object notation parse function to create an object from a JSON string. We now have an object called user that’s exactly the same as the object we created initially.

Persisting objects in HTML 5 is pretty straight forward and, potentially, very powerful. Although there will always be a place for SQL storage in HTML 5 this persistence method can come in handy when there isn’t a lot of complex data to store. It can also prevent poor design decisions and over engineering simple tasks.

3 Responses to “HTML 5 Object Persistance”

  1. John Tantalo says:

    http://emend.appspot.com/sites/openbit.co.uk/edits/0

    “restore the object to it’s previous state” should be “restore the object to its previous state”

  2. Eric says:

    Please hold the background still. I can’t read.

  3. Thanks for the info.

Leave a Reply