如何更新JSON文件?

2024-04-28 13:12:20 发布

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

我有一些代码将数据存储在字典中,而字典存储在JSON文件中:

def store_data(user_inp):

list_of_letters = list(user_inp)
list_of_colons = []
nested_dict = {}

for letter in list_of_letters:
    if letter == ':':
        list_of_colons.append(letter)

jf = json.dumps(storage)
with open('myStorage.json', 'w') as f:
    f.write(jf)

if len(list_of_colons) == 2:
    str1 = ''.join(list_of_letters)
    list2 = str1.split(':')
    main_key = list2[0]
    nested_key = list2[1]
    value = list2[2]
    if main_key not in storage:
        storage[main_key] = nested_dict
        nested_dict[nested_key] = value
        print(storage, '\n', 'successfully saved!')
        jf = json.dumps(storage)
        with open('myStorage.json', 'w') as f:
            f.write(jf)

    elif main_key in storage:
        if nested_key in storage[main_key]:
            print('this item is already saved: \n', storage)
        else:
            storage[main_key][nested_key] = value
            print(storage, '\n', 'successfully saved!')
            jf = json.dumps(storage)
            with open('myStorage.json', 'w') as f:
                f.write(jf)

问题是,每次我重新运行程序并输入新数据时,JSON文件中的数据都会被上次运行程序时输入的数据替换。例如:如果我想存储这个字符串:gmail:pass:1234。我的职能是: 使用用户输入创建字典并将其存储在JSON文件中:

{'gmail': {'pass': 1234}}

只要我不关闭程序,我输入的数据就会不断添加到JSON对象中。但如果我关闭程序,再次运行,然后输入新数据,我之前存储的数据将被我上次输入的数据替换

所以我想要的是,每当我向字典中输入一段新数据时,它都会将其添加到JSON文件中存储的对象中。因此,如果我再次运行该程序并输入此输入,gmail:pass2:2343,则它的存储方式如下:

{'gmail': {'pass': '1234', 'pass2': '2343'}}

如果我输入zoom:id:1234567,我希望它将其添加到JSON文件中的对象中,如下所示:

{'gmail': {'pass': '1234', 'pass2': '2343'} 'zoom': {'id': '1234567'}}

我真的不知道如何解决这个问题,我已经研究过了,但我找不到解决我具体案例的方法

希望你明白我的意思。提前感谢您的帮助


Tags: 文件of数据keyinjsonif字典
1条回答
网友
1楼 · 发布于 2024-04-28 13:12:20

我想这就是你想要做的:

def update_with_item(old, new_item):
    changed = True
    top_key, nested_key, value = new_item
    if top_key in old:
        if nested_key in old[top_key]:
            changed = False
            print("This item is already saved: \n", storage)
        else:
            old[top_key][nested_key] = value
    else:
        old[top_key] = {nested_key: value}
    return old, changed


def main():
    stored = json.load(open('myStorage.json'))
    old, changed = update_with_item(stored, list2)
    if changed:
        jf = json.dumps(old)
        with open('myStorage.json', 'w') as f:
            f.write(jf)
        print(storage, '\n', 'successfully saved!')

我也不确定如何在main中循环代码,或者list2变量来自何处。这里的主要功能需要更新,以了解如何循环创建新值等

update_with_item函数应该可以解决您在更新字典时遇到的问题

相关问题 更多 >