I am trying to write a json inside a ZipFile BytesIO process. It goes like this:
JavaScript
x
10
10
1
import io
2
from zipfile import ZipFile
3
import json
4
5
in_memory_zip = io.BytesIO()
6
with ZipFile(in_memory_zip, 'w') as zipfile:
7
with zipfile.open("1/1.json", 'w') as json_file:
8
data = {'key': 1}
9
json.dump(data, json_file, ensure_ascii=False, indent=4)
10
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:
JavaScript
1
11
11
1
import io
2
from zipfile import ZipFile
3
import json
4
5
in_memory_zip = io.BytesIO()
6
with ZipFile(in_memory_zip, 'w') as zf:
7
with zf.open("1/1.json", 'w') as json_file:
8
data = {'key': 1}
9
data_bytes = json.dumps(data, ensure_ascii=False, indent=4).encode('utf-8')
10
json_file.write(data_bytes)
11