Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

json

I want to convert such query string:

a=1&b=2

to json string

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

Any existing solution?

like image 730
Bin Chen Avatar asked Aug 11 '12 07:08

Bin Chen


People also ask

How do I convert a string to a JSON in Python?

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.

Can we convert string to JSON?

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.


2 Answers

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.

like image 89
Tomalak Avatar answered Sep 17 '22 19:09

Tomalak


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"]}
like image 31
kamarkiewicz Avatar answered Sep 16 '22 19:09

kamarkiewicz