convert cookies to json javascript 1

convert cookies to json javascript

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

Here is what the above code is Doing:
1. We have a string of cookies.
2. We split the string into an array of key-value pairs.
3. We iterate over the array and split each pair into a key and a value.
4. We assign the key to the output object and the value to the key.
5. We stringify the output object.

The output is:

{
“referer”: “example.com/post?id=22”,
“bcomID”: “8075”,
“subreturn”: “example&fuzzy=true&ct=null&autobounce=true”,
“JSESSIONID”: “6D20570E1EB”,
“mbox”: “session”
}

Similar Posts