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?
With the help of gzip. compress(s) method, we can get compress the bytes of string by using gzip. compress(s) method. Return : Return compressed string.
With the help of gzip. decompress(s) method, we can decompress the compressed bytes of string into original string by using gzip. decompress(s) method. Return : Return decompressed string.
The most important difference is that gzip is only capable to compress a single file while zip compresses multiple files one by one and archives them into one single file afterwards. Thus, gzip comes along with tar most of the time (there are other possibilities, though). This comes along with some (dis)advantages.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With