As you’ve seen, you can store data as a string in the web storage systems, and that is it. It’s fine if you want to store a single number, or a string. But what about more complex data, which is harder to convert to a string.
Converting Data to JSON Strings
Well, using JSON (JavaScript Object Notation) is becomes much easier.
There are lots of ways to store JSON data. Let’s look at a simple example, where we create a generic object, and add some properties based upon data from an example form using jQuery.
var person = new Object();
person.name = $('#firstName').val() + ' ' + $('#lastName').val()
person.age = $('#age').val()
// ....
// convert the JS Object into a JSON string
strPerson = JSON.stringify(person)
localStorage.setItem("person", strPerson );
Likewise we can work with an array in a similar manner.
var myArray = [2,4,6,8];
strArray = JSON.stringify(myArray);
localStorage.setItem("sampleArray", strArray );
Converting Strings back to JSON
To convert the data back into a JavaScript object so we can work with it, we need to parse the string.
var person = JSON.parse(localStorage.getItem("person"));
var array2 = JSON.parse(localStorage.getItem("sampleArray"));
// now you can work with the data as needed.
Web Storage in HTML5 – Complex Data was originally found on Access 2 Learn