将字典保存到json fi

2024-10-03 15:31:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试通过以下代码片段保存dictionary to json文件。 我找不到这个网站的答案来解决这个问题。在

怎么了?在

dic = { b'pejorative': 0, b'greek': 1, b'from': 2, b'english': 3, b'and': 4 ... } 
json.dump(dic, 
        open(os.path.join(path, 'model_dict.json'), 'wb'), 
        ensure_ascii=False)) 

或者

^{pr2}$

Tags: and文件topath答案代码fromjson
3条回答

我也有同样的问题。如果需要将“多维”dict转换为UTF:

def convert2utf( data):
    converted_object={}
    for key, value in data.items():
        if (not isinstance(value, dict)) and (not isinstance(value, list)):
            converted_object[key.decode()]=value.decode()
        elif isinstance(value, dict):
            converted_object[key.decode()]=convert2utf(value)
        else:
            sub_list=[]
            for next_item in value:
                sub_list.append(convert2utf(next_item))
            converted_object[key.decode()]=sub_list
    return converted_object

官方文件明确宣称

The json module always produces str objects, not bytes objects. Therefore, fp.write() must support str imput

实际上,在python中,字符串以str对象的形式存储在内存中,如果需要,可以使用.decode()编码序列

怎么了?好吧,错误信息中的所有字母都写了:

TypeError: key b'pejorative' is not a string

dict键是bytestring(比较前面的b''),而json.dump()希望它们是(unicode)字符串。在

解决方法是使用从bytestrings解码的unicode字符串重建dict,即:

dic = {key.decode():value for key, value in dic.items()} 

但是,如果您的任何键包含除utf-8之外的任何内容(utf-8是bytes.decode()的默认编码),则可能会引发此问题。在

真正的解决方案当然是修复最初填充 所以从一开始就使用unicode字符串。在

相关问题 更多 >