Skip to content
Advertisement

How to json dump inside Zipfile.open process?

I am trying to write a json inside a ZipFile BytesIO process. It goes like this:

import io
from zipfile import ZipFile
import json

in_memory_zip = io.BytesIO()
with ZipFile(in_memory_zip, 'w') as zipfile:
    with zipfile.open("1/1.json", 'w') as json_file:
        data = {'key': 1}
        json.dump(data, json_file, ensure_ascii=False, indent=4)

It is later saved in a Django File field. However it does not dump the data into the json_file. Finds it hard since it does not report an error message.

Advertisement

Answer

Your code ‘shadows’ zipfile, which won’t be a problem by itself, but would cause problems if you needed zipfile later in your code. In general, don’t shadow standard library identifiers and Python keywords.

Why it’s a problem, I don’t know, but it appears json.dump expects something from the file pointer that the file-like object that ZipFile.open() gets you doesn’t have.

This is how to get around that:

import io
from zipfile import ZipFile
import json

in_memory_zip = io.BytesIO()
with ZipFile(in_memory_zip, 'w') as zf:
    with zf.open("1/1.json", 'w') as json_file:
        data = {'key': 1}
        data_bytes = json.dumps(data, ensure_ascii=False, indent=4).encode('utf-8')
        json_file.write(data_bytes)
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement