将Python 3.x字典保存为JSON

3

这个答案中提出的解决方案可以将一个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

根据这个答案,解决方案是某种类型的转换;但我无法为字典执行此操作。在Python 3.x中正确保存dictjson的方法是什么?
1个回答

8

去掉b标签:

with open('data.json', 'w') as fp:
    json.dump(data, fp)

json.dump

json 模块总是生成 str 对象,而不是 bytes 对象。因此,fp.write() 必须支持 str 输入。


请问您能否添加一些参考资料?我在文档中该如何找到这个解决方案? - Dror

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接