14

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 ?

1 Answer 1

35

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

Sign up to request clarification or add additional context in comments.

2 Comments

You could also write json.loads(user.body), in case that user.body is a binary object that represent a python's dictionary.
you are a diamond mate!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.