Search code examples
jsonpython-requeststornado

JSON.loads gives a string output when invoked in tornado handler


I am passing some data to a tornado server handler which calls json.loads(request.body) This is how request.body looks like:

b'"{\\"inputs\\": {\\"key1\\": \\"/9j/4QxgRXhpZgAATU0AKgAAAAgA....... sVf/2Q==\\"}}"'

When I call json.loads on this request.body this is what the output looks like

payload = json.loads(request.body)
print(payload)
{"inputs": {"key1": "/9j/4QxgRXhpZgAATU.....rsVf/2Q=="}}
print(type(payload)) # <class 'str'>
payload2 = json.loads(payload)
print(type(payload2 )) # <class 'dict'>

I am not sure why the output of json.loads is str

This is the request body I am passing

with open("ee", "rb") as image_file:
    encoded_string = base64.b64encode(image_file.read())

x = {"inputs": {"key1": encoded_string.decode("utf-8")}}
<request_session>.post(<HOST>, json=json.dumps(x))

How can I change my request body such that when json.loads is called on my request.body, I recieve a dictionary

The handler is built in tornado


Solution

  • The data you're receiving is json encoded twice. So you'll need to decode it twice on the server to get the dict.

    The problem is the way you're sending the data from the client. If you see the docs of requests, the json argument should be a json serializable object, not already serialized object.

    That means requests is also encoding your json data once more.

    Try passing the dict without json encoding:

    <request_session>.post(<HOST>, json=x)