简体   繁体   English

将python 3.x字典保存到JSON

[英]Save a python 3.x dictionary to JSON

The solution suggested in this answer allows saving a dict into json . 这个答案中建议的解决方案允许将dict保存到json For instance: 例如:

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

However, this doesn't work with 3.x . 但是,这不适用于3.x I get the following error: 我收到以下错误:

TypeError: 'str' does not support the buffer interface

According to this answer , the solution is some sort of cast; 根据这个答案 ,解决方案是某种演员; but I don't manage to do it for a dictionary. 但我无法为字典做这件事。 What's the right way to save a dict to json using python 3.x? 使用python 3.x将dict保存到json的正确方法是什么?

remove the b : 删除b

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

json.dump 那样json.dump

The json module always produces str objects, not bytes objects. json模块总是生成str对象,而不是字节对象。 Therefore, fp.write() must support str input. 因此,fp.write()必须支持str输入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM