当字节不是json / object格式时,如何将字节类型转换为dict?
示例
request.body = b'Text=this&Voice=that'
之类的
request.body => {'Text' : 'this', 'Voice' : 'that'}
Python 3.5或3.6?
答案 0 :(得分:3)
由于应该对名称和值中的=和&进行编码,因此您可以执行以下操作:
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'}
答案 1 :(得分:2)
使用标准的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
中是不寻常的,但是如果存在,这就是您的处理方式。)