Question

I am trying to save a python dictionary in a cookie and then be able to convert the cookie value back to a dict in jquery or javascript. I'm using python 3.3.1. I'm getting confused on formats ( query strings, json, etc).

I'm using this jquery cookie library

https://github.com/carhartl/jquery-cookie

I have tried the following:

server side:

import urlib.parse
d= {'key1':'value1','key2':'value2'}
cookie_data = urllib.parse.urlencode(d)

client side:

cookie_data = $.cookie('Cookie_Name');
var dict = $.parseJson(cookie_data);

What is the correct way of doing it so I end up with a valid dictionary on the client side?

I also have tried using:

server side:

d = {'key1':'value1','key2':'value2'}
cookie_data = json.dumps(d)

Which gets me the desired json data in a string.

cookie_data now is '{"key1":"value1","key2":"value2"}'

However when I send it as a cookie the string comes out like this

"\173\"key2\": \"value2\"\054 \"key1\": \"value1\"\175"

That's why I thought I needed to encode it somehow.

I have also tried:

var cookie_str = $.cookie('My_cookie');
var decoded_cookie = decodeURIComponent(cookie_str);

both cookie_str and decoded_cookie are the same

\173"key2": "value2"\054 "key1": "value1"\175

Was it helpful?

Solution

I figured it out by doing this server side:

import urlib.parse, json
cookie_data = urllib.parse.quote(json.dumps(mydict))

client side using jquery

var dict = $.parseJSON($.cookie('MyCookie'));

OTHER TIPS

Using console logging in JS can be very useful to debug what info is being sent back and forth.

console.log(cookie_data)

will print what is actually stored in $.cookie('Cookie_Name');

The problem here is that you're storing url-encoded values in the server: key1=value1&key2=value2, but you want the json: {"key1": "value1", "key2": "value2"}. You need to encode the data into JSON format on the server, as that's what the client is expecting.

repr will get you close, but it uses single-quotes and the JSON standard specifies double-quotes for strings. Your client may accept this, but to conform to the standard, as well as escaping other data, you should use a python library for encoding JSON, such as simplejson:

>>> simplejson.JSONEncoder().encode({'k':'v', 'k2': 'v2'})
'{"k2": "v2", "k": "v"}'
>>> repr({'k':'v', 'k2': 'v2'})
"{'k2': 'v2', 'k': 'v'}"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top