9

I am trying to do the following with Python3:

data = json.dumps(packet)
s = StringIO()
g = gzip.GzipFile(fileobj=s, mode='w')
g.write(data)
g.close()
gzipped_body = s.getvalue()

But it keeps complaining with the following error:

TypeError: string argument expected, got 'bytes'

The example code I'm using is based on Python2 so I am thinking there is some changes in StringIO that might be causing this but I'm not sure. Anyone give me some hints on how to get a gzipped string of some JSON in Python3?

1 Answer 1

19

Looks like this might have gotten a lot easier in Python3. This code seems to work so far:

data = bytes(json.dumps(packet), 'utf-8')
s_out = gzip.compress(data)
Sign up to request clarification or add additional context in comments.

1 Comment

bytes() is an easy way to convert StringIO()'s .getvalue() string to bytes! Then you can gzip it.

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.