我有一个应用程序,我需要将 Python 搁置腌制字典文件转换为 JSON 文件。
import ujson, shelve
with open("shelveFile", "r") as sfile:
shelve_dict=shelve.open(sfile)
py_dict= dict(shelve_dict)
with open("jsonfile.json","w") as jsonfile:
ujson.dump(py_dict, jsonfile)
with open("jsonfile.json",'r') as readJSONfile:
ujson.loads(readJSONfile.read())
注意:如果我使用ujson.load(jsonfile2)
我会得到一个序列化错误。
我遇到的问题:搁置文件对某些字典键使用 Python 元组数据类型。我可以用来ujson.dump
保存为 JSON,但是当我尝试使用ujson.load(jsonfile)
键时,它们会被加载为字符串而不是元组。缺少使用字典理解来转换键(不确定确切的语法),是否有一个库可以将搁置文件转换为我可以加载回 Python 字典对象的 JSON 文件?
通过ujson.loads(fileobj.read())
方法加载时:
{"('tuplekey1','tuplekey2')": value,}
应该:
{('tuplekey1','tuplekey2'): value,}
(如果问题不清楚,请不要投票,如果需要,我会尽力澄清......我不经常在这里发布问题。)