最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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 plex serialization/deserialization altogether?

Thanks

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 plex serialization/deserialization altogether?

Thanks

Share Improve this question asked Jul 15, 2010 at 4:11 Michael WaxmanMichael Waxman 1,8253 gold badges18 silver badges33 bronze badges 1
  • Are you sure the cookie is getting stored properly? What is the value of document.cookie? – Anurag Commented Jul 15, 2010 at 4:17
Add a ment  | 

2 Answers 2

Reset to default 4

Cookies are separated by mas, 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, '"%2C"');

And no modification is needed in decoding

发布评论

评论列表(0)

  1. 暂无评论