我有一个flask
服务。有时候我会收到没有指向http
标头的json
消息。在这种情况下,我尝试从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
?
user.body
是代表Python字典的二进制对象,您也可以编写json.loads(user.body)
。 - Franco Gil