Bin Chen
Bin Chen

Reputation: 63299

python: how to convert a query string to json string?

I want to convert such query string:

a=1&b=2

to json string

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

Any existing solution?

Upvotes: 20

Views: 23415

Answers (5)

Olivier Lasne
Olivier Lasne

Reputation: 981

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

Upvotes: 0

Tomalak
Tomalak

Reputation: 338148

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.

Upvotes: 48

kamarkiewicz
kamarkiewicz

Reputation: 116

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

Upvotes: 6

shivg
shivg

Reputation: 762

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

Upvotes: 0

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250891

>>> strs="a=1&b=2"

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

Upvotes: 7

Related Questions