[英]How to parse binary string to dict ?
I have flask
-service. 我有
flask
服务。 Sometimes I can get json
message without a point at http
header. 有时候,我可以在
http
标头处获得没有点的json
消息。 In this case I'm trying to parse message from request.data
. 在这种情况下,我正在尝试解析
request.data
消息。 But the string from request.data
is really hard thing to parse. 但是来自
request.data
的字符串真的很难解析。 It's a binary string like this: 这是一个二进制字符串,如下所示:
b'{\n "begindate": "2016-11-22", \n "enddate": "2016-11-22", \n "guids": ["6593062E-9030-B2BC-E63A-25FBB4723ECC", \n "5A9F8478-6673-428A-8E90-3AC4CD764543", \n "D8243BA1-0847-48BE-9619-336CB3B3C70C"]\n}'
When I'm trying to use json.loads()
, I'm getting this error: 当我尝试使用
json.loads()
,我收到此错误:
TypeError: the JSON object must be str, not 'bytes'
Function of converting to string ( str()
) doesn't work good too: 转换为字符串(
str()
)的功能也不能很好地工作:
'b\'{\\n "begindate": "2016-11-22", \\n "enddate": "2016-11-22", \\n "guids": ["6593062E-9030-B2BC-E63A-25FBB4723ECC", \\n "5A9F8478-6673-428A-8E90-3AC4CD764543", \\n "D8243BA1-0847-48BE-9619-336CB3B3C70C"]\\n}\''
I use Python 3
. 我使用
Python 3
。 What can I do to parse request.data
? 我该怎么做才能解析
request.data
?
Just decode
it before passing it to json.loads
: 在
decode
它传递给json.loads
之前decode
它:
b = b'{\n "begindate": "2016-11-22", \n "enddate": "2016-11-22", \n "guids": ["6593062E-9030-B2BC-E63A-25FBB4723ECC", \n "5A9F8478-6673-428A-8E90-3AC4CD764543", \n "D8243BA1-0847-48BE-9619-336CB3B3C70C"]\n}'
r = json.loads(b.decode())
print(r)
{'begindate': '2016-11-22',
'enddate': '2016-11-22',
'guids': ['6593062E-9030-B2BC-E63A-25FBB4723ECC',
'5A9F8478-6673-428A-8E90-3AC4CD764543',
'D8243BA1-0847-48BE-9619-336CB3B3C70C']}
Python 3.x makes a clear distinction between the types: Python 3.x明确区分了类型:
str
= '...'
literals = a sequence of Unicode characters (UTF-16 or UTF-32, depending on how Python was compiled) str
= '...'
literals =一系列Unicode字符(UTF-16或UTF-32,具体取决于Python的编译方式)
bytes
= b'...'
literals = a sequence of octets (integers between 0 and 255) bytes
= b'...'
literals =一个八位字节序列(0到255之间的整数)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.