7

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.

sidarcy
  • 2,958
  • 2
  • 36
  • 37

2 Answers2

10

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

This:

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

should probably do it.

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
  • the \ wont replace, when I try string.replace('\054', ',') I get back the same string – sidarcy Jan 03 '14 at 15:57
  • backslash not ment to be replaced, try double back-slash \\ – Ori Refael Jan 03 '14 at 16:11
  • +1 as you are correct the \054 was breaking the JSON, now just to figure out why i cant replace it :/ – sidarcy Jan 03 '14 at 17:44
  • my bad... for the ease of asking the question i only show 2 items in the JSON, in reality there is a lot of data. Your answer is correct however it just replaced a single instance of \054. str.replace(/\\054/g, ",") did the trick thanks for your help – sidarcy Jan 03 '14 at 17:50
  • I'll add that to the answer :) Glad to be of some help. – Cerbrus Jan 03 '14 at 17:52
8

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

Community
  • 1
  • 1
Frogmouth
  • 1,808
  • 1
  • 14
  • 22
  • 2
    +1 for the info on 'allowed cookies', i was hoping to create something on the server that i could easily parse as JSON on the client, Python is not making it easy – sidarcy Jan 03 '14 at 17:04