20

I want to convert such query string:

a=1&b=2

to json string

{"a":1, "b":2}

Any existing solution?

2

5 Answers 5

48

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.

Sign up to request clarification or add additional context in comments.

4 Comments

In other words convert the qs to a dict and then convert that dict to json
For Python 3 users: urlparse is now called urllib.parse
Could be imported as from urllib import parse as urlparse without changing the rest of the code.
If you need to parse as single values then parse_qsl can be used - dict(urlparse.parse_qsl('a=1&b=2')) yields '{"a": ["1"], "b": ["2"]}'
7
>>> strs="a=1&b=2"

>>> {x.split('=')[0]:int(x.split('=')[1]) for x in strs.split("&")}
{'a': 1, 'b': 2}

2 Comments

@BinChen there's no syntax error. which python version are you using?
This syntax is available in Python 2.7+ and 3+. Use d = dict((key, value) for (key, value) in iterable) in 2.6 and earlier
6

Python 3.x

from json import dumps
from urllib.parse import parse_qs

dumps(parse_qs("a=1&b=2"))

yelds

{"b": ["2"], "a": ["1"]}

Comments

0
dict((itm.split('=')[0],itm.split('=')[1]) for itm in qstring.split('&'))

Comments

0

In 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]"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.