I want to convert such query string:
a=1&b=2
to json string
{"a":1, "b":2}
Any existing solution?
I want to convert such query string:
a=1&b=2
to json string
{"a":1, "b":2}
Any existing solution?
Python 3+
import json
from urllib.parse import parse_qs
json.dumps(parse_qs("a=1&b=2"))
Python 2:
import json
from urlparse import parse_qs
json.dumps(parse_qs("a=1&b=2"))
In both cases the result is
'{"a": ["1"], "b": ["2"]}'
This is actually better than your {"a":1, "b":2}, because URL query strings can legally contain the same key multiple times, i.e. multiple values per key.
urlparse is now called urllib.parsefrom urllib import parse as urlparse without changing the rest of the code.parse_qsl can be used - dict(urlparse.parse_qsl('a=1&b=2')) yields '{"a": ["1"], "b": ["2"]}'>>> strs="a=1&b=2"
>>> {x.split('=')[0]:int(x.split('=')[1]) for x in strs.split("&")}
{'a': 1, 'b': 2}
d = dict((key, value) for (key, value) in iterable) in 2.6 and earlierIn Python 2 & 3:
import json
def parse_querystring(query_string):
variables = dict()
for item in query_string.split('&'):
key, value = item.split('=')
# if value is an int, parse it
if value.isdigit():
value = int(value)
variables[key] = value
return variables
query_string = 'user=john&uid=10&[email protected]'
qs = parse_querystring(query_string)
print(repr(qs))
print(json.dumps(qs))
The result is
{'user': 'john', 'uid': 10, 'mail': '[email protected]'}
{"user": "john", "uid": 10, "mail": "[email protected]"