Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parse / convert cookie to JSON format

Tags:

javascript

Have we any javascript library or regex to parse / convert cookies to JSON format?

Some cookies like this:

cookie=referer=example.com/post?id=22;bcomID=8075; subreturn=example&fuzzy=true&ct=null&autobounce=true; JSESSIONID=6D20570E1EB; mbox=session
like image 465
ali Avatar asked May 09 '15 10:05

ali


People also ask

Can cookie contain JSON?

Storing JSON in cookies will increase the size of cookie unnecessarly, which effects your web apps performance. After a long time I fired up Firebug, which lead to a realization of mistake we done by storing JSON in cookies. I think Firebug is best to check cookie more than Chrome Devtools.

How do I set JSON object in cookie?

We can convert a JSONObject to cookie using the toString() method and convert a cookie to JSONObject using the toJSONObject() method of org. json. Cookie class.


1 Answers

You can try this:

var cookie = "referer=example.com/post?id=22;bcomID=8075; subreturn=example&fuzzy=true&ct=null&autobounce=true; JSESSIONID=6D20570E1EB; mbox=session";
var output = {};
cookie.split(/\s*;\s*/).forEach(function(pair) {
  pair = pair.split(/\s*=\s*/);
  output[pair[0]] = pair.splice(1).join('=');
});
var json = JSON.stringify(output, null, 4);
console.log(json);

EDIT:

If the cookie have %NUM characters you can wrap name and value with decodeURIComponent:

var output = {};
cookie.split(/\s*;\s*/).forEach(function(pair) {
  pair = pair.split(/\s*=\s*/);
  var name = decodeURIComponent(pair[0]);
  var value = decodeURIComponent(pair.splice(1).join('='));
  output[name] = value;
});
like image 131
jcubic Avatar answered Oct 03 '22 04:10

jcubic