I have to compress the list of dictionary using gzip and send as request parameter to a backend API. While using the gzip library i couldn't send the json because everytime I get a bad request from the server. Here is an example of the data:
[{'name':'John'}, {'name': 'Clark'}]
First I tried using the version 1 of the code below but I always get a
TypeError: string argument expected, got 'bytes'
So, I tried version 2 which returns a bad request.There is another similar answer but I need to do this with a file-object. Could you point out where I am going wrong?
Version 1
import gzip
import json
import io
inp1 = {"name": "John"}
inp2 = {"name": "Clark"}
final_inp = []
final_inp.append(inp1)
final_inp.append(inp2)
print(final_inp)
data = json.dumps(final_inp)
out = io.StringIO()
with gzip.GzipFile(fileobj=out, mode="w") as f:
f.write(data)
res = out.getvalue()
print(res)
Version 2
# same imports and declartion from version 1
# this code works but i have to do it using version 1.
data = json.dumps(final_inp)
out = io.BytesIO()
with gzip.GzipFile(fileobj=out, mode="wb") as f:
f.write(data.encode())
res = out.getvalue()
print(res)