I'm using jQuery's $.post()
method to post JSON data, specifically I'm posting an array.
$.post('/my/url/',{my_list:['foo','bar','foo baz']})
I've read in the docs that the post
method will use the $.param
method to serialize JSON objects given to it as data. The jQuery docs seem to imply that their method of serialization is开发者_运维百科 an oft-used standard (at least in Ruby on Rails and PHP), but I can't seem to find any convenient modules/methods that automagically un-serialize $.param
in Python.
What's the easiest way to un-param-
aterize this data in Python? More specifically, I'm using Google App Engine.
Thanks!
EDIT: Added my_list
key to data.
Figured it out!
In Google App Engine in particular the get_all
method of the Request
object handles JSON arrays serialized with jQuery's .param
method.
The slightly confusing part is that jQuery tacks []
on to the end of the parameter key. As such, the Python code which you use is...
class MyListHandler(webapp.RequestHandler):
def post(self):
print self.request.get_all('my_list[]') # <-- Note the `[]`
...this will print...
[u'foo', u'bar', u'foo baz']
I believe JQuery $.post()
sends url-encoded form variables to the server, not JSON key-values. So this:
$.post('/foo', {foo: "bar", nums: [1, 2, 3]})
Results in the following application/x-www-form-urlencoded
data being posted
to /foo
:
foo=bar&nums%5B%5D=1&nums%5B%5D=2&nums%5B%5D=3
Which you can parse in Python using urlparse.parse_qs
:
>>> import urlparse
>>> urlparse.parse_qs('foo=bar&nums%5B%5D=1&nums%5B%5D=2&nums%5B%5D=3')
{'foo': ['bar'], 'nums[]': ['1', '2', '3']}
jquery-unparam handles nested data structures better than urlparse! E.g.:
// as produced by $.get, $.post etc
$.param({a: 1, b: [2,3,4], c: { d: 5 } })
"a=1&b%5B%5D=2&b%5B%5D=3&b%5B%5D=4&c%5Bd%5D=5"
Python by jquery_unparam vs. urlparse.parse_qs:
>>> from jquery_unparam import jquery_unparam
>>> jquery_unparam("a=1&b%5B%5D=2&b%5B%5D=3&b%5B%5D=4&c%5Bd%5D=5")
{'a': '1', 'c': {'d': '5'}, 'b': ['2', '3', '4']}
>>> from urlparse import parse_qs
>>> parse_qs("a=1&b%5B%5D=2&b%5B%5D=3&b%5B%5D=4&c%5Bd%5D=5")
{'a': ['1'], 'b[]': ['2', '3', '4'], 'c[d]': ['5']}
精彩评论