如何将此JSON对象存储为cookie,而不是在vanilla javascript中读取它? [英] How do I store this JSON object as a cookie and than read it in vanilla javascript?

查看:88
本文介绍了如何将此JSON对象存储为cookie,而不是在vanilla javascript中读取它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实际上可能像这样的cookie写得很好:

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

但是如何读取Cookie?



我使用node.js / express.js(和咖啡脚本),当我读取cookie键值我得到的只是上述数组的第一个值。 / p>

我需要解析吗?

解决方案

Cookie由逗号分隔,因此当您存储JSON时,它被分解为多个Cookie。



例如,您可以使用JSON字符串替换JSON字符串,然后将JSON字符串替换为 ,部分如下:

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

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

显然,这不是一个通用的解决方案,因为您需要确保被替换的字符串不会出现in the content(even escaped)


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

解决方案

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)

这篇关于如何将此JSON对象存储为cookie,而不是在vanilla javascript中读取它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆