当字节不是json/对象格式时,如何将字节类型转换为dict?
示例request.body = b'Text=this&Voice=that'
到类似的东西
request.body=>{'Text' : 'this', 'Voice' : 'that'}
Python 3.5或3.6?
由于=和&在应该编码的名称/值中,您可以执行以下操作:
r = b'Text=this&Voice=that'
postdata = dict(s.split(b"=") for s in r.split(b"&"))
print(postdata)
以上应输出:
{b'Text': b'this', b'Voice': b'that'}
如果你想去掉字节:
r = b'Text=this&Voice=that'
r = r.decode("utf-8") #here you should add your encoding, with utf-8 you are mostly covered for ascii as well
postdata = dict([s.split("=") for s in r.split("&")])
print(postdata)
应该打印的:
{'Text': 'this', 'Voice': 'that'}
使用标准parse_qs
:
from urllib.parse import parse_qs
from typing import List, Dict
s = request.body.decode(request.body, request.charset)
query:Dict[str,List[str]= parse_qs(s)
(这个查询字符串在request.body
中是不寻常的,但如果是,这就是你的做法。(