我有 - 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'
转换为string(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
?
只是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']}
Python 3.x明确区分了类型:
str
= '...'
literals =一系列Unicode字符(UTF-16或UTF-32,具体取决于Python的编译方式)
bytes
= b'...'
literals =一个八位字节序列(0到255之间的整数)
链接了解更多信息