fao*_*xis 6 python json python-3.x
我有 - 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}'
Run Code Online (Sandbox Code Playgroud)
当我尝试使用时json.loads(),我收到此错误:
TypeError: the JSON object must be str, not 'bytes'
Run Code Online (Sandbox Code Playgroud)
转换为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}\''
Run Code Online (Sandbox Code Playgroud)
我用Python 3.我该怎么办才能解析request.data?
Jim*_*ard 16
只是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']}
Run Code Online (Sandbox Code Playgroud)
Python 3.x明确区分了类型:
str= '...'literals =一系列Unicode字符(UTF-16或UTF-32,具体取决于Python的编译方式)
bytes= b'...'literals =一个八位字节序列(0到255之间的整数)