将一系列字典保存到json文件并稍后检索

时间:2017-04-05 08:03:09

标签: json python-3.x dictionary

所以我在python中做了一些工作,我必须生成一系列字典。我想把这些词典写成一个文件。

编写词典的代码看起来像这样

with open('some_name.json', 'w') as fh:
    data = function_generate_dict() # returns a dictionary
json.dump(data, fh)

工作正常,我可以查看输出的文件,甚至可以像这样加载其内容

with open('some_name.json', 'r+') as rh:
    for line in rh.readlines():
        print(line)

但是当我尝试通过执行此操作从文件重新加载每个字典时

with open('some_name', 'r') as rh:
    cont = rh.read()
js =json.loads(cont)

我总是得到JSONDecodeError: Extra data: line 1 column 220 (char 219)  我怀疑它来自一个字典结束而另一个字典开始的地方。

如果我这样做(json.load() instead of json.loads()

with open('some_name', 'r') as rh:
    cont = rh.read()
js =json.load(cont)

我收到此错误AttributeError: 'str' object has no attribute 'read' 我甚至尝试使用jsonl作为文件格式。但它不起作用。

以下是我正在生成的词典示例

{"measure_no": "0", "divisions": "256", "fifths": "5", "mode": "major", "beats": "4", "beat-type": "4", "transpose": "-9", "step": ["G"], "alter": ["1"], "octave": ["6"], "duration": ["256"], "syllabic": [], "text": []}{"measure_no": "1", "divisions": "256", "fifths": "5", "mode": "major", "beats": "4", "beat-type": "4", "transpose": "-9", "step": ["G", "G", "G", "G"], "alter": ["1", "1", "1", "1"], "octave": ["6", "6", "6", "6"], "duration": ["384", "128", "256", "256"], "syllabic": [], "text": []}{"measure_no": "2", "divisions": "256", "fifths": "5", "mode": "major", "beats": "4", "beat-type": "4", "transpose": "-9", "step": ["C", "G", "G"], "alter": ["1", "1", "1"], "octave": ["7", "6", "6"], "duration": ["384", "128", "512"], "syllabic": [], "text": []}

1 个答案:

答案 0 :(得分:0)

您的代码会将字典转储到现有行的末尾:

这是1:难以为人类阅读。 2:很难阅读" readlines"功能

转储词典后添加新行。

with open('some_name.json', 'a') as fh:
''' note the use of 'a' instead of 'w', you want to append your 
    dictionnaries, not overwrite them every time '''
    data = function_generate_dict() # returns a dictionary
    json.dump(data, fh)
    fh.write('\n')

然后当你想读取:从文件到字典:你可以用循环读取每一行作为不同的json字典: 我会看到它的方式是先制作一个空的词典来存储每一行​​。

jsonlist = []
'''make a list to store the json dictionaries'''
with open('some_name','r') as rh:
    for line in rh.readlines():
        jsonlist.append(json.loads(line))

你现在有了变量jsonlist,每个索引都是你的json词典之一,剩下的就是操作那些索引。

>>> jsonlist[0]
{'measure_no': '0', 'divisions': '256', 'fifths': '5', 'mode': 'major', 'beats': '4', 'beat-type': '4', 'transpose': '-9', 'step': ['G'], 'alter': ['1'], 'octave': ['6'], 'duration': ['256'], 'syllabic': [], 'text': []}