faoxis
faoxis

Reputation: 2022

How to parse binary string to dict ?

I have flask-service. Sometimes I can get json message without a point at http header. In this case I'm trying to parse message from request.data. But the string from request.data is really hard thing to parse. 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:

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

Function of converting to string (str()) doesn't work good too:

'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. What can I do to parse request.data ?

Upvotes: 14

Views: 23431

Answers (1)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160647

Just decode it before passing it to 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 makes a clear distinction between the types:

  • str = '...' literals = a sequence of Unicode characters (UTF-16 or UTF-32, depending on how Python was compiled)

  • bytes = b'...' literals = a sequence of octets (integers between 0 and 255)

Link for more info

Upvotes: 34

Related Questions