I want to convert such query string:
a=1&b=2
to json string
{"a":1, "b":2}
Any existing solution?
you can turn it into JSON in Python using the json. loads() function. The json. loads() function accepts as input a valid string and converts it to a Python dictionary.
String data can be easily converted to JSON using the stringify() function, and also it can be done using eval() , which accepts the JavaScript expression that you will learn about in this guide.
import json
import urlparse
json.dumps(urlparse.parse_qs("a=1&b=2"))
yields
'{"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.
from json import dumps
from urllib.parse import parse_qs
dumps(parse_qs("a=1&b=2"))
yelds
{"b": ["2"], "a": ["1"]}
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