如何解析二进制字符串到dict?

时间:2017-01-12 06:33:27

标签: 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}'

当我尝试使用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

1 个答案:

答案 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之间的整数)

Link for more info

相关问题