我有flask
- 服务。有时,我可以在json
标题处获得http
消息,而无需点。在这种情况下,我试图解析来自request.data
的消息。但是来自request.data
的字符串真的难以解析。它是一个二进制字符串,如下所示:
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}'
当我尝试使用json.loads()
时,我收到此错误:
TypeError: the JSON object must be str, not 'bytes'
转换为字符串(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}\''
我使用Python 3
。我该怎么做才能解析request.data
?
答案 0 :(得分:14)
在将decode
传递给json.loads
之前,只需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']}
:
str
Python 3.x明确区分了类型:
'...'
= bytes
literals =一系列Unicode字符(UTF-16或UTF-32,具体取决于Python的编译方式)
b'...'
= UIButton
literals =一个八位字节序列(0到255之间的整数)