andrewschwap
andrewschwap

Reputation: 27

How to convert a query string to valid json?

Is there an easy way to convert a query parameter string such as 'username=andrew&password=password1234' to valid JSON { "username": "andrew", "password": "password1234" }

I have been trying to loop through the string and manually add parameters to JSON but I am curious to know if there is an easier way or a library available.

Upvotes: 1

Views: 1347

Answers (2)

buran
buran

Reputation: 14233

using urllib.parse.parse_qsl

import urllib.parse
import json
spam = 'username=andrew&password=password1234'
eggs = urllib.parse.parse_qsl(spam)
print(eggs)
foo = dict(eggs) # dict
print(foo)
bar =  json.dumps(foo) # JSON string
print(repr(bar))

output

[('username', 'andrew'), ('password', 'password1234')]
{'username': 'andrew', 'password': 'password1234'}
'{"username": "andrew", "password": "password1234"}'

Note: this is assuming only unique keys.

Upvotes: 2

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

You can parse this to a dictionary that maps keys to a list of values:

from urllib.parse import parse_qs

data = parse_qs('username=andrew&password=password1234')

this will give us:

>>> parse_qs('username=andrew&password=password1234')
{'username': ['andrew'], 'password': ['password1234']}

This is because a key can occur multiple times. If you are sure it only occurs once per key, you can use dictionary comprehension to convert it to a single item:

from urllib.parse import parse_qs

data = { k: v
    for k, vs in parse_qs('username=andrew&password=password1234').items()
    for v in vs
}

and this produces:

>>> { k: v
...     for k, vs in parse_qs('username=andrew&password=password1234').items()
...     for v in vs
... }
{'username': 'andrew', 'password': 'password1234'}

You can make use of json.dumps(…) [python-doc] to convert it to a JSON blob:

>>> print(dumps(data))
{"username": "andrew", "password": "password1234"}

Upvotes: 4

Related Questions