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.
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:
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
:) i hope it can help...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With