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



Question:

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

 ["4c3dd477c441e17957000002","4c2ac3cc68fe54616e00002e","4c3dd477c441e17957000003","4c3dd477c441e17957000004"]  

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?

Thanks


Solution:1

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)


Solution:2

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
Previous
Next Post »