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

蹲街弑〆低调 提交于 2019-12-12 17:40:41

问题


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


回答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)




回答2:


I think you can just encode like this:

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

And no modification is needed in decoding



来源:https://stackoverflow.com/questions/3252400/how-do-i-store-this-json-object-as-a-cookie-and-than-read-it-in-vanilla-javascri

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!