JSON JavaScript cookies
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:
dataattribute - stores the data you want to save,save()method, andload()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.
This entry was posted on Wednesday, September 27th, 2006 and is filed under JavaScript, JSON. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
Get notification for future posts: follow me on Twitter or subscribe to my RSS feed

September 30th, 2006 at 10:53 am
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
September 14th, 2007 at 1:08 am
This is most excellent! Simple, effective, and useful!
February 20th, 2008 at 2:06 pm
Nice method to save a window setting easily.
nice jobe guys ! thanks
October 2nd, 2008 at 4:45 am
Thanks for your solution
It’s Great
November 13th, 2008 at 3:30 pm
He funny, i just made this also… without knowing about this article
December 15th, 2008 at 3:19 pm
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.
March 23rd, 2009 at 12:50 pm
This does not work anymore.
You get a javascript error with IE
August 7th, 2009 at 7:55 am
Really nice implementation. I’ll try ASAP
October 27th, 2009 at 10:00 pm
[...] 9.http://www.phpied.com/json-javascript-cookies/ [...]
November 16th, 2009 at 12:30 pm
[...] JSON JavaScript cookies @ [...]
November 17th, 2009 at 4:27 pm
[...] 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 [...]
May 5th, 2010 at 10:46 am
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?
April 5th, 2011 at 6:12 pm
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();
}
}
August 1st, 2011 at 4:53 am
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]));
August 6th, 2011 at 6:58 am
Do not forget the size limit of cookies!
November 21st, 2011 at 5:21 pm
Watch The Simpsons – Season 23, Episode 6: The Book Job…
[...]JSON JavaScript cookies / Stoyan’s phpied.com[...]…