Javascript:解析document.cookie JSON对象的问题

时间:2022-08-26 11:28:04

On the server I'm storing a JSON object as a cookie (using Django / json.dumps), it looks like so:

在服务器上我将一个JSON对象存储为cookie(使用Django / json.dumps),它看起来像这样:

'{"name": "Simon", "gender": "M"}'

On the client when I run document.cookie I can see the cookie and it looks like so:

在我运行document.cookie的客户端上,我可以看到cookie,它看起来像这样:

"user="{\"name\": \"Simon\"\054 \"gender\": \"M\"}";

I have a small function which retrieves a cookie by name ( getCookie('user') )it returns a string:

我有一个小函数,它按名称检索cookie(getCookie('user'))它返回一个字符串:

"{\"name\": \"Simon\"\054 \"gender\": \"M\"}"

I want to parse this back to a JSON object for further use on the client however JSON.parse() returns the error: "SyntaxError: Unexpected number".

我想将其解析回JSON对象以便在客户端上进一步使用,但是JSON.parse()返回错误:“SyntaxError:Unexpected number”。

Whats strange is if you run the following:

如果你运行以下内容,那有多奇怪:

JSON.parse("{\"name\": \"Simon\"\054 \"gender\": \"M\"}") 

directly in the console it works fine. Any ideas?

直接在控制台中它工作正常。有任何想法吗?

If there is a better way to store the cookie etc im open to ideas

如果有更好的方式存储cookie等我对想法开放

Thanks in advance.

提前致谢。

2 个解决方案

#1


7  

The \054 is breaking your json. it's a encoded , (comma).

\ 054打破了你的json。它是一个编码的,(逗号)。

This:

这个:

string.replace(/\\054/g, ',');

should probably do it.

应该这样做。

#2


6  

Comma is an illegal character in Cookie... and is not the only one, for prevent problem maybe you can encode your JSON befoure put in cookie:

逗号是Cookie中的非法字符...并且不是唯一的一个,为了防止问题,也许你可以编码你的JSON befoure放入cookie:

encodeURIComponent('{"name": "Simon", "gender": "M"}');
//return "%7B%22name%22%3A%20%22Simon%22%2C%20%22gender%22%3A%20%22M%22%7D"

decodeURIComponent('%7B%22name%22%3A%20%22Simon%22%2C%20%22gender%22%3A%20%22M%22%7D');
//return '{"name": "Simon", "gender": "M"}'

This answer explains better the world of "allowed character" in cookie: Allowed characters in cookies

这个答案更好地解释了cookie中“允许字符”的世界:cookie中允许的字符

:) i hope it can help...

:)我希望它可以帮助...

#1


7  

The \054 is breaking your json. it's a encoded , (comma).

\ 054打破了你的json。它是一个编码的,(逗号)。

This:

这个:

string.replace(/\\054/g, ',');

should probably do it.

应该这样做。

#2


6  

Comma is an illegal character in Cookie... and is not the only one, for prevent problem maybe you can encode your JSON befoure put in cookie:

逗号是Cookie中的非法字符...并且不是唯一的一个,为了防止问题,也许你可以编码你的JSON befoure放入cookie:

encodeURIComponent('{"name": "Simon", "gender": "M"}');
//return "%7B%22name%22%3A%20%22Simon%22%2C%20%22gender%22%3A%20%22M%22%7D"

decodeURIComponent('%7B%22name%22%3A%20%22Simon%22%2C%20%22gender%22%3A%20%22M%22%7D');
//return '{"name": "Simon", "gender": "M"}'

This answer explains better the world of "allowed character" in cookie: Allowed characters in cookies

这个答案更好地解释了cookie中“允许字符”的世界:cookie中允许的字符

:) i hope it can help...

:)我希望它可以帮助...