简体   繁体   English

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

[英]How to parse binary string to dict ?

I have flask -service. 我有flask服务。 Sometimes I can get json message without a point at http header. 有时候,我可以在http标头处获得没有点的json消息。 In this case I'm trying to parse message from request.data . 在这种情况下,我正在尝试解析request.data消息。 But the string from request.data is really hard thing to parse. 但是来自request.data的字符串真的很难解析。 It's a binary string like this: 这是一个二进制字符串,如下所示:

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}'

When I'm trying to use json.loads() , I'm getting this error: 当我尝试使用json.loads() ,我收到此错误:

TypeError: the JSON object must be str, not 'bytes'

Function of converting to string ( str() ) doesn't work good too: 转换为字符串( 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}\''

I use Python 3 . 我使用Python 3 What can I do to parse request.data ? 我该怎么做才能解析request.data

Just decode it before passing it to json.loads : decode它传递给json.loads之前decode它:

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 makes a clear distinction between the types: Python 3.x明确区分了类型:

  • str = '...' literals = a sequence of Unicode characters (UTF-16 or UTF-32, depending on how Python was compiled) str = '...' literals =一系列Unicode字符(UTF-16或UTF-32,具体取决于Python的编译方式)

  • bytes = b'...' literals = a sequence of octets (integers between 0 and 255) bytes = b'...' literals =一个八位字节序列(0到255之间的整数)

Link for more info 链接了解更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM