[英]How to json dump inside Zipfile.open process?
我正在嘗試在 ZipFile BytesIO 進程中編寫 json 。 它是這樣的:
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)
它稍后保存在 Django 文件字段中。 但是,它不會將數據dump
到json_file
中。 發現很難,因為它不報告錯誤消息。
您的代碼 'shadows' zipfile
,這本身不會成為問題,但如果您稍后在代碼中需要zipfile
,則會導致問題。 通常,不要隱藏標准庫標識符和 Python 關鍵字。
為什么這是一個問題,我不知道,但看起來json.dump
期望來自文件指針的東西,而ZipFile.open()
獲得的類文件對象沒有。
這是解決這個問題的方法:
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)
原始代碼失敗的原因是ZipFile
期望二進制數據作為輸入,而json.dump
期望接受“文本”數據( str
,而不是bytes
)的類似文件的 object 。 您可能會想到zf.open()
返回的 object 就好像它是以"wb"
模式打開的文件一樣。
所以這里正確的做法是包裝類似文件的 object 以呈現面向文本的 output 到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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.