JSON JavaScript cookies

September 27th, 2006. Tagged: JavaScript, JSON

Here's a little thing I came up with, which hopefully can make reading/writing cookies with JavaScript easier.

The big idea

The idea is to keep a JavaScript object (a hash array) of all little variable things you want to store in a cookie. Then, once ready, you encode the object into a JSON string and save it to a cookie. To load the data from a previously saved cookie, you decode the JSON string back into an object.

The tiny implementation

Having the little JSON lib from json.org, it's very easy. The solution was to have an object called prefs (the idea initially came when I wanted to save user preferences), which has:

  • data attribute - stores the data you want to save,
  • save() method, and
  • load() method.

The code is as follows:

var prefs = {
 
    data: {},
 
    load: function () {
        var the_cookie = document.cookie.split(';');
        if (the_cookie[0]) {
            this.data = unescape(the_cookie[0]).parseJSON();
        }
        return this.data;
    },
 
    save: function (expires, path) {
        var d = expires || new Date(2020, 02, 02);
        var p = path || '/';
        document.cookie = escape(this.data.toJSONString())
                          + ';path=' + p
                          + ';expires=' + d.toUTCString();
    }
 
}

Using the prefs object

In order to use this you need to satisfy dependencies first, including json.js and prefs.js:

<script type="text/javascript" src="json.js"></script>
<script type="text/javascript" src="prefs.js"></script>

Then you're ready to do save()s and load()s. If you need to delete a cookie, you call save() with date in the past. Here are some examples:

// save
prefs.data.something = "one"; // save one
// ... do other stuff ...
prefs.data.another = "two";
// ready to store?
prefs.save();
 
 
// another syntax
var to_save = {
    one: 1,
    two: 2,
}
prefs.data = to_save;
prefs.save();
 
 
// delete
var date_in_the_past = new Date(2000,02,02);
prefs.save(date_in_the_past);
 
 
// read
var what = prefs.load();
// load populates prefs.data and also returns
alert(what.something);
// or ...
alert(prefs.data.something);

Thanks

Thank you for reading! As always, any comments are appreciated.

Comments? Find me on BlueSky, Mastodon, LinkedIn, Threads, Twitter