Tutorial :How do I store this JSON object as a cookie and than read it in vanilla javascript?


I can actually seem to write it fine as a cookie like this:


But how do I read the cookie?

I'm using node.js/express.js (and coffee script), and when I read it the cookie key the value I get is just the first value of the above array.

Do I need to parse it somehow? Or a more complex serialization/deserialization altogether?



Cookies are separated by commas, so when you store the JSON it is being broken up into multiple cookies. You will need to encode the JSON string some way before writing to the Cookie and then decode when reading.

For example, you could take the JSON string and replace the '","' parts like this:

// encode  mycookie = json.replace(/","/g, '"-"');    // decode  json = mycookie.replace(/"-"/g, '","');  

Obviously this is no a general solution as you would need to insure that the strings being replaced do not appear in the content (even escaped)


I think you can just encode like this:

// encode  mycookie = json.replace(/","/g, '"2%C"');  

And no modification is needed in decoding

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »