How to attach a gz file to a json object in python?

Viewed 48

I have an api that returns a gz file. The application from where I am running the api accepts only json formats. Is there a way to attach the returned gz file to a json object? Would converting the gz file to base64 format and then creating a json object like { "file": "the base64 format" } work?

print(json.dumps({'file': base64.b64decode(response_alert.content)}))

I get the error

Object of type bytes is not JSON serializable
1 Answers

String encoding is str→bytes and decoding is bytes→str. Base64 is the reverse, as it encodes binary data as characters rather than characters as binary data. However, since many of its use cases involve ASCII protocols like SMTP, base64.b64encode actually requires and returns bytes (ASCII in the latter case). You therefore want

json.dumps(dict(file=base64.b64encode(response_alert.content).decode()))

which takes advantage of the default encoding (UTF-8) supporting ASCII text. On the other end, you don’t have to bother encoding back to bytes, since str is accepted by base64.b64decode.

Related