+2  A: 

The Storage API stores a key, value pairs both of which are strings. So they need to be serialized somehow, and later deserialized when retrieving. In your example, you are using JSON as the (de)serialization mechanism.

getItem will always return the string you stored. It has to be deserialized before you get an object out of it. You can modify the native getItem function and do the (de)serialization internally, or write a wrapper for localStorage that does it for you. Please read the other answers before you re-post the question. That is what the other answers were saying. They did not say that you must use jQuery. Writing a wrapper is fairly simple.

var MyLocalStorage = {};

MyLocalStorage.getItem = function(key) {
    return JSON.parse(localStorage.getItem(key));
};

MyLocalStorage.setItem = function(key, object) {
    localStorage.setItem(key, JSON.stringify(object));
};
Anurag
+2  A: 

Anurag's suggestion sounds like the best way to go about it (Mozilla Hacks demonstrates the other option he outlines), but to take it a little further and make it chainable, you could do something like:

var MyLocalStorage = {};

MyLocalStorage.getItem = function(key) {
    return new MyItem(JSON.parse(localStorage.getItem(key)));
};

MyLocalStorage.setItem = function(key, object) {
    localStorage.setItem(key, JSON.stringify(object));
    return this.getItem(key);
};

function MyItem(object, key) {
    this.item = object;
    this.key = key;
    this.addSubItem = function(subItem) {
        if (typeof this.item.push == 'function') {
            this.item.push(subItem);
            this.save();
            return this;
        }
        return false;
    };
    this.setItem = function(object) {
        this.item = object;
        this.save();
        return this;
    };
    this.save = function() {
        MyLocalStorage.setItem(this.key, this.item);
    };
    this.toString = function() {
        return this.item.toString();
    }
}

Then you could use it like:

alert(
    MyLocalStorage
        .setItem('names', ['john', 'paul', 'ringo'])
        .addSubItem('george')
        .toString()
);

BTW: It's almost impossible to find official documentation on the LocalStorage object (e.g. on MDC or any other online JS documentation library).

Lèse majesté