Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Problems parsing document.cookie JSON object

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.

like image 807
sidarcy Avatar asked Jan 03 '14 15:01

sidarcy


2 Answers

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

This:

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

should probably do it.

like image 117
Cerbrus Avatar answered Oct 19 '22 18:10

Cerbrus


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...

like image 23
Frogmouth Avatar answered Oct 19 '22 18:10

Frogmouth