Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
179
rated 0 times [  180] [ 1]  / answers: 1 / hits: 27459  / 9 Years ago, sat, may 9, 2015, 12:00:00

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

More From » javascript

 Answers
32

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;
});

[#66664] Thursday, May 7, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
isaacvalentinn

Total Points: 325
Total Questions: 120
Total Answers: 131

Location: North Korea
Member since Tue, Jun 16, 2020
4 Years ago
isaacvalentinn questions
Mon, Jan 18, 21, 00:00, 3 Years ago
Mon, Nov 23, 20, 00:00, 4 Years ago
Wed, Sep 23, 20, 00:00, 4 Years ago
;