[英]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" }
有没有一种简单的方法可以将查询参数字符串(例如
'username=andrew&password=password1234'
{ "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.我一直在尝试遍历字符串并手动将参数添加到 JSON 但我很想知道是否有更简单的方法或可用的库。
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:您可以使用
json.dumps(…)
[python-doc]将其转换为 JSON blob:
>>> print(dumps(data))
{"username": "andrew", "password": "password1234"}
using urllib.parse.parse_qsl使用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 output
[('username', 'andrew'), ('password', 'password1234')]
{'username': 'andrew', 'password': 'password1234'}
'{"username": "andrew", "password": "password1234"}'
Note: this is assuming only unique keys.注意:这是假设只有唯一的键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.