this answer 中建议的解决方案允许将 dict
保存到 json
中。例如:
import json
with open('data.json', 'wb') as fp:
json.dump(data, fp)
但是,这不适用于 3.x
。我收到以下错误:
TypeError: 'str' does not support the buffer interface
根据 this answer ,解决方案是某种类型的转换;但我没有设法为字典做这件事。使用 python 3.x 将 dict
保存到 json
的正确方法是什么?
最佳答案
删除b
:
with open('data.json', 'w') as fp:
json.dump(data, fp)
json 模块总是生成 str 对象,而不是 bytes 对象。所以fp.write()必须支持str输入。
关于python - 将 python 3.x 字典保存到 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28541705/