简体   繁体   English

Python:将字典附加到 JSON 列表:

[英]Python: Appending dictionary to JSON list:

I would like to create a list of dictionaries in my JSON file.我想在我的 JSON 文件中创建一个字典列表。 The problem, though, is that JSON does not append new data properly.但是,问题是 JSON 没有正确地 append 新数据。 Here is my code:这是我的代码:

import json

json_data = [
    {
    'name': 'Luke',
    'age': 27
    },
    {
    'name': 'Harry',
    'age': 32
    },
    ]
with open('data.json', 'a+') as file:
    json.dump(json_data, file)

JSON just creates another whole list at each appending attempt: JSON 只是在每次追加尝试时创建另一个完整列表:

[
    {"name": "Luke", "age": 27}, 
    {"name": "Harry", "age": 32}
][
    {"name": "Luke", "age": 27}, 
    {"name": "Harry", "age": 32}
][
    {"name": "Luke", "age": 27}, 
    {"name": "Harry", "age": 32}
]

I want to have one single list that holds all these dictionaries.我想要一个包含所有这些字典的列表。 Here's an example of how it SHOULD be like ideally:这是一个理想情况下的示例:

[
    {"name": "Luke", "age": 27}, 
    {"name": "Harry", "age": 32},
    {"name": "Luke", "age": 27}, 
    {"name": "Harry", "age": 32},
    {"name": "Luke", "age": 27}, 
    {"name": "Harry", "age": 32},
]

How do I create something like that?我该如何创造这样的东西? Thank you for all your help: :)谢谢你的帮助: :)

Quick fix solution with eval() :使用eval()快速修复解决方案:

import json

json_data = [
    {
    'name': 'Luke',
    'age': 27
    },
    {
    'name': 'Harry',
    'age': 32
    },
    ]

with open('data.json', 'r+') as file:  # read and append
    stored_info = eval(file.readline())  # using eval() to convert list in file to an actual list
    for i in stored_info:
        json_data.append(i)
    file.seek(0)  # clear file
    json.dump(json_data, file)

However, this will only work if data.json exists and already contains information.但是,这只有在data.json存在并且已经包含信息时才有效。 You might have to check if data.json exists(which means there will already be information if only program edits data.json ):您可能需要检查data.json是否存在(这意味着如果只有程序编辑data.json就会有信息):

...
try: 
    with open('data.json', 'r+') as file:  # read and append
        stored_info = eval(file.readline())  # using eval() to convert list in file to an actual list
        for i in stored_info:
            json_data.append(i)
        file.seek(0)  # clear file
        json.dump(json_data, file)
except:  # data.json doesn't exist
    with open('data.json', 'w') as file:
        json.dump(json_data, file)

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

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