I am creating my own api interface for my python application (for whatever reason :))
I am able to get my request body in a form-data string e.g
"name=prakashraman&tvshows%5B%5D=lost&tvshows%5B%5D=buffy"
I would like that be converted to
{
"name": "prakashraman",
"tvshows": ["lost", "buffy"]
}
Any ideas on how I could go about this?
Here's one naive way to do this:
s = "name=prakashraman&tvshows%5B%5D=lost&tvshows%5B%5D=buffy"
d = {}
for x in s.split('&'):
k, sep, v = x.partition('=')
if sep != '=':
raise ValueError('malformed query')
k = k.split('%')[0]
if k in d:
if isinstance(d[k], list): d[k].append(v)
else: d[k] = [d[k], v]
else:
d[k] = v
print(d)
# {'name': 'prakashraman', 'tvshows': ['lost', 'buffy']}
However, if you need to keep your output standardised as a QueryDict, the easy way is to use urllib.parse.parse_qs (in Python 2: urlparse.parse_qs) on the string:
>>> from urllib import parse
>>> s = "name=prakashraman&tvshows%5B%5D=lost&tvshows%5B%5D=buffy"
>>> parse.parse_qs(s)
{'name': ['prakashraman'], 'tvshows[]': ['lost', 'buffy']}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With