Javascript:解析document.cookie JSON对象时出现问题 [英] Javascript: Problems parsing document.cookie JSON object

查看:466
本文介绍了Javascript:解析document.cookie JSON对象时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 '{name:Simon,gender:M}'

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

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

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

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

我想将它解析回一个JSON对象,供客户端使用, ()返回错误:SyntaxError:Unexpected number。



如果运行以下命令,会出现以下错误:

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

直接在控制台中工作正常。 b

如果有更好的方式来存储cookie等等。



提前感谢。

解决方案

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



这:

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

应该可以。


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

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

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

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

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

"{\"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".

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

Thanks in advance.

解决方案

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

This:

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

should probably do it.

这篇关于Javascript:解析document.cookie JSON对象时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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