Cookie Jar: Yummy JSON Cookies (using Prototype)

on Thursday, April 12th, 2007 at 12:39 pm

JavaScript code to store data as JSON strings in cookies. It uses prototype.js to store and retrieve JSON data from cookies.

Now we can store and retrieve JavaScript Objects, Arrays, Boolean, String, Number values using cookies, just like storing Java Objects in session on the server side.

Works with Firefox 1.5, 2.0, IE 6.0 and Opera 9.10.

Example

(Execute this example)

jar = new CookieJar({
expires:3600,   // seconds
path: '/'
});
 
dog = {name: 'Jacky', breed: 'Alsatian', age:5};
 
jar.put('mydog', dog);
mydog = jar.get('mydog');
 
alert("My dog's name is " + mydog.name);
alert("He is " + mydog.age + " years old");
alert("He is an " + mydog.breed);

Download

You can view the source code here.
This code is released under CC Attribution-ShareAlike 2.5.

API

CookieJar(options)
Constructor. Takes in a object as options.

options = {
expires: '',  // time in seconds (defualt: 3600)
path: '',     // cookie path
domain: '',   // cookie domain
secure: ''    // secure ?
}

boolean put(string name, mixed value)
Puts a particular cookie in the cookie jar. The cookie is associated with the name. Returns false if cannot add cookie (Ex: max cookie size exceeded!). Returns true on success.

mixed get(string name)
Gets a particular cookie from the cookie jar. Returns null if not found.

boolean remove(string name)
Removes a particular cookie from the cookie jar. Returns true on success, false otherwise.

void empty()
Empties the Cookie Jar.

array getKeys()
Gets array of all the cookie names.

object getPack()
Gets all the cookies as a single JavaScript object (Package) with name value pairs.

Change Log

v 0.4 (11-Aug-07)

  1. Removed a extra comma in options (was breaking in IE and Opera). (Thanks Jason)
  2. Removed the parameter name from the initialize function
  3. Changed the way expires date was being calculated. (Thanks David)

v 0.3 (22-Jun-07)

  1. Removed dependancy on json.js (http://www.json.org/json.js)
  2. empty() function only deletes the cookies set by CookieJar. Leaves alone other cookies like session_id etc.

v 0.2 (12-Apr-07)

  1. Released for public use.

Related

13 Responses to “Cookie Jar: Yummy JSON Cookies (using Prototype)”

  1. kangax Says:

    Very nice.
    Could you please submit this to http://scripteka.com

    Thanks.

  2. Lalit Says:

    @kangax:
    I already have :)
    Thanks!

  3. Carros Brasilia Says:

    Hi Lalit, thank for you script. Very nice and clean.

  4. William Says:

    Very slick piece of code - I’m developing a couple of applications at the moment where I’m using this - it’s a really clean and well thought out implementation - thanks for sharing it!

  5. Raj Parmar Says:

    Does this support arrays in a json string? I keep getting errors when trying to implement an array in the object.
    eg. It stores the following without a problem:
    jar.put(’test’,{’alpha’:[{'name':'one'},{'name':'two'},{'name','three'}]})

    but when I try to get it (eg. test = jar.get(’test’)), it always returns a string and not an object. So I can’t get the value of test.alpha[0].name.

    Am I doing something wrong?

  6. Raj Parmar Says:

    Correction:
    jar.put(’test’,{’alpha’:[{’name’:'one’},{’name’:'two’},{’name’:'three’}]})

    (but still having problems with it).

  7. Lalit Says:

    Raj, you need to pass the array as a JS object to the function, it will automatically convert it to JSON; and when you do get, it will convert it back to object. You need not pass a JSON encoded string.

  8. Lalit Says:

    Raj,
    2nd post should work. I will test and get back to you.

  9. Raj Parmar Says:

    Hi Lalit, it seems I was suffering the “invalid label” problem (http://willcode4beer.com/tips.jsp?set=jsonInvalidLabel).

    It works a treat now! Thanks!

  10. jeff Says:

    It’s very nice.I like it.

  11. scott Says:

    LOVE this, thank you! doesn’t seem to work in IE6 tho. But I’m using prototype v1.6 - has there been any update? (does not work in IE7 either)

  12. scott Says:

    It was my fault this was not working under IE. >_< Sorry for the mis-information.

  13. Facundo Says:

    Hi, I’m trying to erase the entire cookie, but I cant. You could check my code?
    That created the cookie:
    jar = new CookieJar({expires:3600, path: ‘/’});
    shop = {order_id: results['order_id']};
    jar.put(’shop’, shop);

    And with that, in a function, I try to delete the cookie:

    jar = new CookieJar();
    if (jar.get(’shop’)){
    shop = jar.get(’shop’);
    if (shop.order_id==results['order_id']){
    jar.remove(’shop’);
    }
    }

    Your script its GREAT!!!

Leave a Reply