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?
// another syntax
var to_save = {
    one: 1,
    two: 2,
prefs.data = to_save;
// delete
var date_in_the_past = new Date(2000,02,02);
// read
var what = prefs.load();
// load populates prefs.data and also returns
// or ...


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

Tell your friends about this post: Facebook, Twitter, Google+

20 Responses

  1. This is a great idea – using JSON for serialization of cookie data. Not only does this script make saving complex data easier, it also supersedes the use of multiple cookies on a single website.

    This would be even nicer if it was built to work with Prototype, but I guess that’s up to your readers ;-) Well, the next two weeks I don’t have any school, so I guess I’m going to have a closer look at it…

    BTW: Nice article, as always ;-)

  2. This is most excellent! Simple, effective, and useful!

  3. Nice method to save a window setting easily.
    nice jobe guys ! thanks

  4. Thanks for your solution ;)

    It’s Great ;)

  5. He funny, i just made this also… without knowing about this article :D

  6. This is a cool idea and works great for a short list of preferences as mentioned in this article. However, escaped JSON gets verbose pretty quickly, esp. when you are serializing more complex js objects. Note that if your JSON value is too long, the cookie will fail to write.

  7. This does not work anymore.

    You get a javascript error with IE

  8. Really nice implementation. I’ll try ASAP ;)

  9. [...] 9.http://www.phpied.com/json-javascript-cookies/ [...]

  10. [...] JSON JavaScript cookies @ [...]

  11. [...] voici le code complet dans la page web de ma dream /* * This code is inspired by JSON JavaScript cookies / Stoyan’s phpied.com * and modified for use with prototype * It’s a pretty straight forward way to store and load [...]

  12. I’m trying to implement this on a different platform. Putting json data directly into a cookie will break it. I’ve had to base64 it. Just thought I’d point this out. Also, would there be a better method than base64? What characters are allowed in a cookie string and how do you escape them?

  13. FOR JSON2

    var prefs = {
    data: {},
    load: function () {
    var the_cookie = document.cookie.split(‘;’);
    if (the_cookie[0]) {
    this.data = JSON.parse(unescape(the_cookie[0]));
    return this.data;
    save: function (expires, path) {
    var d = expires || new Date(2030, 02, 02);
    var p = path || ‘/’;
    document.cookie = escape(JSON.stringify(this.data))
    + ‘;path=’ + p
    + ‘;expires=’ + d.toUTCString();

  14. Stoyan, in many situations a ‘global’ cookie will already be in use by underlying frameworks — for example, I am currently working on a .net webforms monstrosity where the first item of document.cookie.split(‘;’) is none of my business.

    In these situations, the JSON parser will break attempting to evaluate key=value pairs.

    Having said that, it’s generally safe to assume that the last item of the arrayified cookie will be the one we’re after. I made the following modification in my implementation:

    this.data = unescape(the_cookie[the_cookie.length-1]).parseJSON();

    …or, using Saurus’ JSON2 syntax:

    this.data = JSON.parse(unescape(the_cookie[the_cookie.length-1]));

  15. Do not forget the size limit of cookies!

  16. Watch The Simpsons – Season 23, Episode 6: The Book Job…

    [...]JSON JavaScript cookies / Stoyan’s phpied.com[...]…

  17. annuaire de la cuisine…

    [...]JSON JavaScript cookies / Stoyan’s phpied.com[...]…

  18. web hosting…

    [...]JSON JavaScript cookies / Stoyan’s phpied.com[...]…

  19. I do trust all of the ideas you’ve offered for your post. They’re really convincing and will certainly work. Still, the posts are very short for novices. May just you please prolong them a bit from next time? Thanks for the post.

  20. This worked for me.


Leave a Reply