当字节不在对象表示法中时,将python字节转换为dict或json

时间:2018-11-18 07:42:10

标签: python python-3.x

当字节不是json / object格式时,如何将字节类型转换为dict?

示例
request.body = b'Text=this&Voice=that'之类的

request.body => {'Text' : 'this', 'Voice' : 'that'}

Python 3.5或3.6?

2 个答案:

答案 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中是不寻常的,但是如果存在,这就是您的处理方式。)