原始代码失败的原因是
ZipFile
期望二进制数据作为输入,而
json.dump
需要一个接受“文本”数据的类文件对象(
str
,不
bytes
). 你可能会想到这个物体
zf.open()
返回时,它就像是一个打开的文件
"wb"
模式。
因此,这里正确的做法是将类似文件的对象包装起来,以呈现面向文本的输出
json.dump
。而且,由于任何文本都必须编码为字节,因此您必须从中获取解决方案
encodings
图书馆。
因此,这是有效的:
import io
from zipfile import ZipFile
import json
import encodings
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_writer = encodings.utf_8.StreamWriter(json_file)
# JSON spec literally fixes interchange encoding as UTF-8: https://datatracker.ietf.org/doc/html/rfc8259#section-8.1
json.dump(data, json_writer, ensure_ascii=False, indent=4)