112

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 $("#ArticlesHolder") like

$.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?

Frits
  • 7,341
  • 10
  • 42
  • 60
Marthin
  • 6,413
  • 15
  • 58
  • 95
  • 8
    Just being pedantic, but there's no "JSON data" in your question. You have some JavaScript objects you've defined via object literal notation (not JSON, JSON is a subset of object literal notation), but there is no JSON there. http://json.org You almost certainly want to *use* JSON as the data format for storing your objects in the cookie string, though. – T.J. Crowder Nov 19 '10 at 12:46

6 Answers6

202

You can serialize the data as JSON, like this:

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

Then to get it from the cookie:

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

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

Christophe Roussy
  • 16,299
  • 4
  • 85
  • 85
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • 3
    JSON is not allowed in cookies for Opera since ancient times http://my.opera.com/community/forums/topic.dml?id=663192&t=1358850781&page=1#comment12828912 I also have this error. Even though if @cookie@ plugin use @encodeURIComponent@, pbug shouldn't appear. – kirilloid Jan 22 '13 at 10:33
  • 1
    This question and answer lead me to believe that `cookie` is an inbuilt function in jQuery. It appears to be not. or is it deprecated..? if it is the plugins i find, linking to it would be great to avoid the confusion... – T J Aug 11 '14 at 16:28
  • 2
    @TJ It is indeed a plugin, the jQuery cookie plugin. You can find it here: http://plugins.jquery.com/cookie/ I really wonder why it's not in core at this point... – Nick Craver Aug 11 '14 at 17:26
  • Be careful using this in some browsers. The `,` (comma) character can cause the cookies to not be set correctly within safari and other browsers. – Matt Seymour Jan 19 '16 at 14:20
  • You can also use this great lightweight cookie library if jQuery is not wanted . [https://developer.mozilla.org/en-US/docs/Web/API/document/cookie] lib – RyBolt Jul 12 '16 at 14:26
  • It seems that commas are disallowed in cookie values as they might be interpreted as separators... https://developer.mozilla.org/en-US/docs/Web/API/document/cookie Would it not be a problem if I directly use `JSON.stringify()`, which might produce commas? – xji Aug 19 '18 at 13:38
  • Seems that using `encodeURLComponent` after `JSON.stringify` solves it. Then when reading the cookie one also needs to first decode it before running `JSON.parse` – xji Aug 19 '18 at 14:10
40

Now there is already no need to use JSON.stringify explicitly. Just execute this line of code

$.cookie.json = true;

After that you can save any object in cookie, which will be automatically converted to JSON and back from JSON when reading cookie.

var user = { name: "name", age: 25 }
$.cookie('user', user);
...

var currentUser = $.cookie('user');
alert('User name is ' + currentUser.name);

But JSON library does not come with jquery.cookie, so you have to download it by yourself and include into html page before jquery.cookie.js

Community
  • 1
  • 1
Vitalii Korsakov
  • 45,737
  • 20
  • 72
  • 90
  • 3
    I tried this approach without $.cookie.json = true and got [object object] as my cookie value. Then set it to true and tried to pass the object directly to the cookie and no cookie was populated. – JacobRossDev Aug 26 '13 at 18:51
  • @jacobross85 I think it's possible that some of us might be using an older version of jquery.cookie.js, please check the source code, sometimes the wrong file is active. – Dexter Jan 08 '15 at 17:52
  • Please note this will cause cookies to be universally treated as JSON. As a result, blindly adding `$cookie.json = true` can cause conflicts with your other cookies. So be careful using this on a project that already uses cookies elsewhere! – Eric Tjossem Sep 04 '15 at 18:46
  • do you have any solution for complex json? i have an json array in my json which some attributes contains json and .... – nasim jahednia Nov 18 '18 at 16:52
7

use JSON.stringify(userData) to coverty json object to string.

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

and for getting back from cookie use JSON.parse()

var data=JSON.parse($.cookie("basket-data"))
prabeen giri
  • 803
  • 7
  • 18
XMen
  • 29,384
  • 41
  • 99
  • 151
5

It is not good practice to save the value that is returned from JSON.stringify(userData) to a cookie; it can lead to a bug in some browsers.

Before using it, you should convert it to base64 (using btoa), and when reading it, convert from base64 (using atob).

val = JSON.stringify(userData)
val = btoa(val)

write_cookie(val)
fragilewindows
  • 1,394
  • 1
  • 15
  • 26
Eyal Ch
  • 9,552
  • 5
  • 44
  • 54
  • 3
    Do you have an reference to a browser that has trouble with this? – Marthin Jun 03 '15 at 08:27
  • 1
    i use a list of jsons as a cookie on chrome on django platform. it has some issues. also, its always better to hide the actual data passed by the cookie from the user – Eyal Ch Jun 03 '15 at 10:22
  • 2
    On the server side, Python's standard cookie handling will reject cookies containing `{` or `}`, and silently drop any cookies that follow the rejected cookie in the cookie header. – snakecharmerb Nov 29 '17 at 16:34
  • Cookie spec in [RFC6265](https://datatracker.ietf.org/doc/html/rfc6265#section-4.1.1) disallows characters such as `"`. This may lead to server ignoring some cookies from the request. – che Oct 21 '21 at 11:33
2

With serialize the data as JSON and Base64, dependency jquery.cookie.js :

var putCookieObj = function(key, value) {
    $.cookie(key, btoa(JSON.stringify(value)));
}

var getCookieObj = function (key) {
    var cookie = $.cookie(key);
    if (typeof cookie === "undefined") return null;
    return JSON.parse(atob(cookie));
}

:)

asimov
  • 71
  • 4
0

Try this one: https://github.com/tantau-horia/jquery-SuperCookie

Quick Usage:

create - create cookie

check - check existance

verify - verify cookie value if JSON

check_index - verify if index exists in JSON

read_values - read cookie value as string

read_JSON - read cookie value as JSON object

read_value - read value of index stored in JSON object

replace_value - replace value from a specified index stored in JSON object

remove_value - remove value and index stored in JSON object

Just use:

$.super_cookie().create("name_of_the_cookie",name_field_1:"value1",name_field_2:"value2"});
$.super_cookie().read_json("name_of_the_cookie");
Community
  • 1
  • 1