python - 将 python 3.x 字典保存到 JSON

标签 python json dictionary

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.dump

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

关于python - 将 python 3.x 字典保存到 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28541705/

相关文章:

python - 创建以动态数量的值作为参数的字典

python - 将嵌套的字典项合并到一个字符串中

python - Python 文本文件中的字典

jQuery。如何执行从 JSON 加载的脚本?

python - 如何在 python 和 Robot-framework 中对字典进行切片?

c# - Dictionary<TKey,TValue>.Values - 它是否分配新的内存和时间复杂度

python - 无法导入 wxPython (Mac)

python - 当类 def 在另一个文件中时使用 Python 装饰器?

php - 在 Flutter 中获取 pHp 数组或 map 作为 JSON 数据?

javascript - 从 PHP 到 JQuery 的 JSON 值并运行函数