views:

48

answers:

2

I have a list of python dictionaries that look like this:

sandwiches = [
    {'bread':'wheat', 'topping':'tomatoes', 'meat':'bacon'},
    {'bread':'white', 'topping':'peanut butter', 'meat':'bacon'},
    {'bread':'sourdough', 'topping':'cheese', 'meat':'bacon'}
]

I want to pass this as a POST parameter to another Django app. What does the client app need to do to iterate through the list?

I want to do something like:

for sandwich in request.POST['sandwiches']:
    print "%s on %s with %s is yummy!" % (sandwich['meat'], sandwich['bread'], sandwich['topping'])

But I don't seem to have a list of dicts when my data arrives at my client app.

+2  A: 

I would use the JSON libraries to serialize your array of dicts into a single string. Send this string as a POST param, and parse the string back into the python datatypes in the Django app using the same library.

http://docs.python.org/library/json.html

aeflash
+2  A: 

You don't say how you're POSTing to the app. My advice would be to serialize the dictionaries as JSON, then simply POST that.

import json, urllib, urllib2
data = json.dumps(sandwiches)
urllib2.urlopen(myurl, urllib.urlencode({'data': data}))

... and on the receiver:

data = request.POST['data']
sandwiches = json.loads(data)
Daniel Roseman