如何最好地将使用 Python shelve 库 (bsddb) 的 Pickled Python 字典转换为具有字典键元组值的 JSON 文件

How Best to Convert a Pickled Python Dictionary Using Python shelve Library (bsddb) to a JSON File that has tuple Values for Dictionary Keys

我有一个应用程序需要将 Python shelve pickled 字典文件转换为 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) 时,键将作为字符串而不是元组加载。 没有使用字典理解来转换键(不确定确切的语法),是否有一个库可以将搁置文件转换为 JSON 文件,我可以将其加载回 Python 字典对象?

通过ujson.loads(fileobj.read())方法加载时:

{"('tuplekey1','tuplekey2')": value,}

应该是:

{('tuplekey1','tuplekey2'): value,} 

(如果问题不明确,请不要投反对票,如果需要,我会尽力澄清......我不经常在这里 post 提问。)

当您想使用 shelvejson 保存数据时,元组不能用作字典键。因此,在您的情况下,使用了元组的字符串表示形式而不是实际的元组 - repr(('tuplekey1', 'tuplekey2')) 给出 "('tuplekey1', 'tuplekey2')".

因此您需要额外的步骤来将字符串解析为元组。例如,eval("('tuplekey1', 'tuplekey2')")tuple(val.strip("()' ") for val in a.split(','))。当然,你需要知道(或识别)哪些字符串应该被解析成元组。

这个问题可以避免 - 数据应该以另一种方式存储 - 另一种元组表示或另一种数据结构。