Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert form-body into dictionary in Python

Tags:

python

regex

http

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?

like image 956
Prakash Raman Avatar asked Dec 07 '25 22:12

Prakash Raman


1 Answers

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']}
like image 186
Moses Koledoye Avatar answered Dec 10 '25 10:12

Moses Koledoye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!