Skip to content

Commit a52398d

Browse files
Merge pull request #10 from js-cookie/auto-json-handling
Add JSON automatic handling Closes gh-10
2 parents 8cdc5c6 + 9adc4da commit a52398d

3 files changed

Lines changed: 152 additions & 30 deletions

File tree

‎README.md‎

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -45,14 +45,14 @@ Cookies.set('name', 'value', { expires: 7, path: '/' });
4545
Read cookie:
4646

4747
```javascript
48-
Cookies.get('name'); // => "value"
48+
Cookies.get('name'); // => 'value'
4949
Cookies.get('nothing'); // => undefined
5050
```
5151

5252
Read all available cookies:
5353

5454
```javascript
55-
Cookies.get(); // => { "name": "value" }
55+
Cookies.get(); // => { name: 'value' }
5656
```
5757

5858
Delete cookie:
@@ -72,6 +72,28 @@ Cookies.remove('name', { path: '/' }); // => true
7272

7373
*Note: when deleting a cookie, you must pass the exact same path, domain and secure options that were used to set the cookie, unless you're relying on the default options that is.*
7474

75+
## JSON
76+
77+
js-cookie provides automatic JSON storage for cookies.
78+
79+
When creating a cookie you can pass an Array or Object Literal instead of a string in the value. If you do so, js-cookie store the string representation of the object according to the `JSON.stringify` api (if available):
80+
81+
```javascript
82+
Cookies.set('name', { foo: 'bar' });
83+
```
84+
85+
When reading a cookie with the default `Cookies.get()` api, you receive the stringified representation stored in the cookie:
86+
87+
```javascript
88+
Cookies.get('name'); // => '{"foo":"bar"}'
89+
```
90+
91+
When reading a cookie with the `Cookies.getJSON()` api, you receive the parsed representation of the string stored in the cookie according to the `JSON.stringify` api (if available):
92+
93+
```javascript
94+
Cookies.getJSON('name'); // => { foo: 'bar' }
95+
```
96+
7597
## RFC 6265
7698

7799
This project assumes [RFC 6265](http://tools.ietf.org/html/rfc6265#section-4.1.1) as a reference for everything. That said, some custom rules are applied in order to provide robustness and cross-browser compatibility.
@@ -120,11 +142,13 @@ If true, the cookie transmission requires a secure protocol (https). Default: `f
120142
Provide a conversion function as optional last argument for reading, in order to change the cookie's value
121143
to a different representation on the fly.
122144

123-
Example for parsing a value into a number:
145+
Example for parsing the value from a cookie generated with PHP's `setcookie()` method:
124146

125147
```javascript
126-
Cookies.set('foo', '42');
127-
Cookies.get('foo', Number); // => 42
148+
// 'cookie+with+space' => 'cookie with space'
149+
Cookies.get('foo', function (value) {
150+
return value.replace(/\+/g, ' ');
151+
});
128152
```
129153

130154
Dealing with cookies that have been encoded using `escape` (3rd party cookies):
@@ -133,8 +157,6 @@ Dealing with cookies that have been encoded using `escape` (3rd party cookies):
133157
Cookies.get('foo', unescape);
134158
```
135159

136-
You can pass an arbitrary conversion function.
137-
138160
## Contributing
139161

140162
Check out the [Contributing Guidelines](CONTRIBUTING.md)

‎src/js.cookie.js‎

Lines changed: 40 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -29,37 +29,52 @@
2929
var unallowedCharsInValue = extend(unallowedChars, {
3030
' ': '%20'
3131
});
32-
function encode(value, charmap) {
32+
33+
function encode (value, charmap) {
3334
for (var character in charmap) {
3435
value = value
3536
.replace(new RegExp(character, 'g'), charmap[character]);
3637
}
3738
return value;
3839
}
3940

40-
function decode(value, charmap) {
41+
function decode (value, charmap) {
4142
for (var character in charmap) {
4243
value = value
4344
.replace(new RegExp(charmap[character], 'g'), character);
4445
}
4546
return value;
4647
}
4748

48-
function parseCookieValue(value) {
49+
function processWrite (value) {
50+
var stringified;
51+
try {
52+
stringified = JSON.stringify(value);
53+
if (/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/.test(stringified)) {
54+
value = stringified;
55+
}
56+
} catch(e) {}
57+
return encode(String(value), unallowedCharsInValue);
58+
}
59+
60+
function processRead (value, converter, json) {
4961
if (value.indexOf('"') === 0) {
5062
// This is a quoted cookie as according to RFC2068, unescape...
5163
value = value.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
5264
}
5365

54-
return decode(value, unallowedCharsInValue);
55-
}
66+
value = decode(value, unallowedCharsInValue);
67+
68+
if (json) {
69+
try {
70+
value = JSON.parse(value);
71+
} catch(e) {}
72+
}
5673

57-
function read(s, converter) {
58-
var value = parseCookieValue(s);
5974
return isFunction(converter) ? converter(value) : value;
6075
}
6176

62-
function extend() {
77+
function extend () {
6378
var key, options;
6479
var i = 0;
6580
var result = {};
@@ -72,15 +87,21 @@
7287
return result;
7388
}
7489

75-
function isFunction(obj) {
90+
function isFunction (obj) {
7691
return Object.prototype.toString.call(obj) === '[object Function]';
7792
}
7893

7994
var api = function (key, value, options) {
95+
var converter;
96+
97+
if (isFunction(value)) {
98+
converter = value;
99+
value = undefined;
100+
}
80101

81102
// Write
82103

83-
if (arguments.length > 1 && !isFunction(value)) {
104+
if (arguments.length > 1 && !converter) {
84105
options = extend(api.defaults, options);
85106

86107
if (typeof options.expires === 'number') {
@@ -89,7 +110,7 @@
89110
}
90111

91112
return (document.cookie = [
92-
encode(key, unallowedCharsInName), '=', encode(String(value), unallowedCharsInValue),
113+
encode(key, unallowedCharsInName), '=', processWrite(value),
93114
options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
94115
options.path ? '; path=' + options.path : '',
95116
options.domain ? '; domain=' + options.domain : '',
@@ -113,21 +134,24 @@
113134
cookie = parts.join('=');
114135

115136
if (key === name) {
116-
// If second argument (value) is a function it's a converter...
117-
result = read(cookie, value);
137+
result = processRead(cookie, converter, this.json);
118138
break;
119139
}
120140

121-
// Prevent storing a cookie that we couldn't decode.
122-
if (!key && (cookie = read(cookie)) !== undefined) {
123-
result[name] = cookie;
141+
if (!key) {
142+
result[name] = processRead(cookie, converter, this.json);
124143
}
125144
}
126145

127146
return result;
128147
};
129148

130149
api.get = api.set = api;
150+
api.getJSON = function() {
151+
return api.get.apply({
152+
json: true
153+
}, [].slice.call(arguments));
154+
};
131155
api.defaults = {};
132156

133157
api.remove = function (key, options) {

‎test/tests.js‎

Lines changed: 83 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// https://github.com/axemclion/grunt-saucelabs#test-result-details-with-qunit
2-
(function() {
2+
(function () {
33
"use strict";
44

55
var log = [];
@@ -216,10 +216,17 @@ test('defaults', function () {
216216
ok(Cookies.set('c', 'v', { path: '/bar' }).match(/path=\/bar/), 'options argument has precedence');
217217
});
218218

219-
test('Quote as the first character in the cookie value', function () {
220-
expect(1);
221-
Cookies.set('c', '"');
222-
strictEqual(Cookies.get('c'), '"', 'should handle the quote character');
219+
test('Quote in the cookie value', function () {
220+
expect(3);
221+
222+
Cookies.set('quote', '"');
223+
strictEqual(Cookies.get('quote'), '"', 'should print the quote character');
224+
225+
Cookies.set('without-last', '"content');
226+
strictEqual(Cookies.get('without-last'), '"content', 'should print the quote character');
227+
228+
Cookies.set('without-first', 'content"');
229+
strictEqual(Cookies.get('without-first'), 'content"', 'should print the quote character');
223230
});
224231

225232
test('RFC 6265 disallowed characters in cookie-octet', function () {
@@ -342,10 +349,79 @@ test('[] used in name', function () {
342349
strictEqual(document.cookie, '', 'delete the cookie');
343350
});
344351

345-
module('conversion', lifecycle);
352+
module('converters', lifecycle);
346353

347-
test('read converter', function() {
354+
test('read converter', function () {
348355
expect(1);
349356
Cookies.set('c', '1');
350357
strictEqual(Cookies.get('c', Number), 1, 'converts read value');
351358
});
359+
360+
module('JSON handling', lifecycle);
361+
362+
test('Number', function () {
363+
expect(2);
364+
Cookies.set('c', 1);
365+
strictEqual(Cookies.getJSON('c'), 1, 'should handle a Number');
366+
strictEqual(Cookies.get('c'), '1', 'should return a String');
367+
});
368+
369+
test('Boolean', function () {
370+
expect(2);
371+
Cookies.set('c', true);
372+
strictEqual(Cookies.getJSON('c'), true, 'should handle a Boolean');
373+
strictEqual(Cookies.get('c'), 'true', 'should return a Boolean');
374+
});
375+
376+
test('Array Literal', function () {
377+
expect(2);
378+
Cookies.set('c', ['v']);
379+
deepEqual(Cookies.getJSON('c'), ['v'], 'should handle Array Literal');
380+
strictEqual(Cookies.get('c'), '["v"]', 'should return a String');
381+
});
382+
383+
test('Array Constructor', function () {
384+
/*jshint -W009 */
385+
expect(2);
386+
var value = new Array();
387+
value[0] = 'v';
388+
Cookies.set('c', value);
389+
deepEqual(Cookies.getJSON('c'), ['v'], 'should handle Array Constructor');
390+
strictEqual(Cookies.get('c'), '["v"]', 'should return a String');
391+
});
392+
393+
test('Object Literal', function () {
394+
expect(2);
395+
Cookies.set('c', {k: 'v'});
396+
deepEqual(Cookies.getJSON('c'), {k: 'v'}, 'should handle Object Literal');
397+
strictEqual(Cookies.get('c'), '{"k":"v"}', 'should return a String');
398+
});
399+
400+
test('Object Constructor', function () {
401+
/*jshint -W010 */
402+
expect(2);
403+
var value = new Object();
404+
value.k = 'v';
405+
Cookies.set('c', value);
406+
deepEqual(Cookies.getJSON('c'), {k: 'v'}, 'should handle Object Constructor');
407+
strictEqual(Cookies.get('c'), '{"k":"v"}', 'should return a String');
408+
});
409+
410+
test('Use String(value) for unsupported objects that do not stringify into JSON', function() {
411+
expect(4);
412+
413+
Cookies.set('date', new Date(2015, 04, 13, 0, 0, 0, 0));
414+
strictEqual(Cookies.get('date').indexOf('"'), -1, 'should not quote the stringified Date object');
415+
strictEqual(Cookies.getJSON('date').indexOf('"'), -1, 'should not quote the stringified Date object');
416+
417+
Cookies.set('function', function (){});
418+
strictEqual(Cookies.get('function'), undefined, 'should return undefined for function object');
419+
strictEqual(Cookies.getJSON('function'), undefined, 'should return undefined for function object');
420+
});
421+
422+
test('Call to read all cookies with mixed json', function () {
423+
Cookies.set('c', { foo: 'bar' });
424+
Cookies.set('c2', 'v');
425+
deepEqual(Cookies.getJSON(), { c: { foo: 'bar' }, c2: 'v' }, 'returns JSON parsed cookies');
426+
deepEqual(Cookies.get(), { c: '{"foo":"bar"}', c2: 'v' }, 'returns unparsed cookies');
427+
});

0 commit comments

Comments
 (0)