Take the 2-minute tour ×

Here's what I am doing,

Get request to my web server, response is in json. Using jquery templates to render that callback data in my app. Pretty straightforward, works like a charm.

Here is the problem: I want to store some of this data locally so that my app doesn't have to fetch it from the server every time (3g is slow and every transaction hurts my UX...). So here is what I've attempted:

   url: app_domain + '/pages/home.json',
   type: 'get',
   datatype: 'json',
   data: { mobile: "1" },
   async: true,
   cache: false,
   success: function(data) {

       //store locally
       localStorage.setItem('foo', data);
       //grab from local store
       var bar = localStorage.getItem('foo');
       // populate template with data
       $.tmpl("cityTemplate", bar).appendTo('#all'); 


This fails. (I realize the code is silly, just for easy debugging until I get it to work)

If I do a simple


after grabbing the locally stored data i see something like

[object, Object],[object, Object],[object, Object],...,[object, Object]

if i do


i get


if i do


i get


So, my best guess is this is caused by the data format getting changed from json to string when stored via localStorage. Would you agree? And, if so, what can I do to get it back into json format?

Thanks a ton!

share|improve this question
add comment

2 Answers

up vote 10 down vote accepted

You need to use JSON like so:

localStorage.setItem('foo', JSON.stringify(data));

And then parse it:

share|improve this answer
ahhh, fantastic. Thanks a ton! –  istan Jun 28 '11 at 19:23
add comment
App.local = (function () {
  var self = {};

  self.get = function (key) {
    var b = localStorage.getItem(key);
    return b ? JSON.parse(b) : null;

  self.set = function (key, value) {
    var b = JSON.stringify(value);
    localStorage.setItem(key, b);

  return self;

Now you have a nice interface to local storage,

var local = App.local;
local.set('foo', 'bar');
var bar = local.get('foo');
share|improve this answer
very nice! thank you! –  istan Jun 28 '11 at 19:33
add comment

Your Answer


