Storing and retrieving JSON objects

153 views
Skip to first unread message

Voltron

unread,
Sep 18, 2012, 1:36:22 PM9/18/12
to Amplify
I cant seem to get objects from a storage:

var storage = UTILS.getStorage();

storage.setItem('test', {'foo':'bar'});
console.log('done', storage.getItem('test').foo); <--- undefined
console.log('done', storage.getItem('done')); [object object] <---
string but not an object

What is the proper way to achieve this?

Thanks

Scott González

unread,
Sep 18, 2012, 1:43:24 PM9/18/12
to ampl...@googlegroups.com
I'm not sure what UTILS is, or what UTILS.getStorage() is returning, but whatever you're using is most certainly not amplify.

Wasim Khan

unread,
Nov 6, 2013, 4:56:48 AM11/6/13
to ampl...@googlegroups.com
Hello Dear,
I have accomplished this by using JSON stringify.
Use following

var store = {
    clear : function (key) {       
        return amplify.store(key, null);
    },

    fetch : function (key) {
        var val = amplify.store(key);
        return JSON.parse(val);        
    },

    save: function (key, value) {
        var val = JSON.stringify(value);
        amplify.store(key, val, expires);
    },
    saveSession: function (key, value) {
        if (!amplify.store.types.sessionStorage) {
            this.save(key, value);
        }
        else {
            var val = JSON.stringify(value);
            amplify.store.sessionStorage(key, val);
        }
    },
    fetchSession: function (key) {
        if (!amplify.store.types.sessionStorage) {
            return this.fetch(key);
        }
        else {
            var val = amplify.store.sessionStorage(key);
            return JSON.parse(val);
        }
    }
};

Hope this will help you and others.
Reply all
Reply to author
Forward
0 new messages