Here is a great answer about how to use json.dumps
to write to a gzip file. What I would like to do is to use the dump
method instead to serialize the json directly into a GzipFile
object.
Example code:
import gzip, json
data = # a dictionary of data here
with gzip.open(write_file, 'w') as zipfile:
json.dump(data, zipfile)
The error raised is
TypeError: memoryview: a bytes-like objet is required, not 'str'
I believe this is caused because the gzip write() method wants a bytes object passed to it. Per the documentation,
The json module always produces str objects, not bytes objects. Therefore, fp.write() must support str input.
Is there a way to wrap the json
string output as bytes so that GzipFile
's write()
will handle it? Or is the only way to do this to use json.dumps
and encode()
the resulting string into a bytes object, as in the other linked answer?
Compressing with gzip As text data, JSON data compresses nicely. That's why gzip is our first option to reduce the JSON data size. Moreover, it can be automatically applied in HTTP, the common protocol for sending and receiving JSON.
dumps() json. dumps() function converts a Python object into a json string.
json. dump() method used to write Python serialized object as JSON formatted data into a file. json. dumps() method is used to encodes any Python object into JSON formatted String.
Another way of writing JSON to a file is by using json. dump() method The JSON package has the “dump” function which directly writes the dictionary to a file in the form of JSON, without needing to convert it into an actual JSON object.
The gzip module supports it out of the box: just declare an encoding and it will encode the unicode string to bytes before writing it to the file:
import gzip
with gzip.open(write_file, 'wt', encoding="ascii") as zipfile:
json.dump(data, zipfile)
Make sure you specify using text mode ('wt'
).
As json has encoded any non ascii character, ascii encoding is enough, but you could use any other encoding compatible with ascii for the first 128 code points like Latin1, UTF-8, etc
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