Save and load object in localStorage

As for the reason only string can be stored in localStorage, an object need to be converted to string format (JSON text).

Save object

var books = [{id:3, name:"From Zero To One"}, {id:4, name:"Head First Java"}];
localStorage.setItem("books", JSON.stringify(books));

Load object

var booksJSON = localStorage.getItem("books");
if( booksJSON == null ){
    // No data stored in the localStorage
var books = JSON.parse(booksJSON);
for(var i=0; i < books.length; ++i) {
    var book = books[i];
    var id =;
    var name =;