Marthin Marthin - 10 months ago 68
jQuery Question

jquery save json data object in cookie

How do I save JSON data in a cookie?

My JSON data looks like this

$("#ArticlesHolder").data('15', {name:'testname', nr:'4',price:'400'});
$("#ArticlesHolder").data('25', {name:'name2', nr:'1', price:'100'});
$("#ArticlesHolder").data('37', {name:'name3', nr:'14', price:'60'});

And I want to do something like

var dataStore = $.cookie("basket-data", $("#ArticlesHolder").data());

and to retrieve the data i want to load it into

$.each($.cookie("basket-data"), function(i,e){
$("#ArticlesHolder").data(i, e);

does anyone know if I'm on the right track or should this be done in some other way? Simply put, how do i put and pull json data from a cookie?

Answer Source

You can seriaize the data as JSON, like this:

$.cookie("basket-data", JSON.stringify($("#ArticlesHolder").data()));

Then to get it from the cookie:


This relies on JSON.stringify() and JSON.parse() to serialize/deserialize your data object, for older browsers (IE<8) include json2.js to get the JSON functionality. This example uses the jQuery cookie plugin