【问题标题】:How to store contents of a dictionary into a json file [duplicate]如何将字典的内容存储到json文件中[重复]
【发布时间】:2018-05-18 19:41:44
【问题描述】:

我有一个字典,每次代码运行时都会使用用户创建的用户名和密码进行更新。每当我运行脚本时,更新的键和值都会成功显示在 JSON 文件中。问题是新的字典值和键替换了 JSON 文件的内容,而不是被添加到其中。

my_dict = {}

# there's code here that utilizes the update method for dictionaries to populate #my_dict with a key and value. Due to its length, I'm not posting it. 

with open('data.json', 'r') as f:
    json_string = json.dumps(my_dict)
    json_string


with open('data.json', 'r') as f:
    json.loads(json_string)


with open('data.json', 'w') as f:
    f.write(json_string)

#these successfully write and save the data to the data.json file. When I run #the script again, however, the new data replaces the old data in my_dict. I #want the new my_dict data to be added instead. How do I do this?

【问题讨论】:

  • 你确定要那个吗?如果文件中有多个串联对象,则该文件将不再是有效的 JSON。您必须跳更多圈才能再次阅读它。
  • 你需要一个对象数组吗?
  • 我需要的是能够遍历 my_dict 并从存储在 data.json 中的 my_dict 条目中获取值

标签: python json file


【解决方案1】:

在写入文件时使用附加状态,例如:

with open('data.json', 'a') as f:
    f.write(json_string)

这将追加字符串而不是完全替换文件。

【讨论】:

    【解决方案2】:

    如果您需要更新您的 JSON 文件只是为了每次保存同一个字典,我认为您的代码可以正常工作。

    但如果你需要一个 JSON 数组,我会在开头插入“[]”。然后在每次迭代中,您可以删除文件的最后一个字符,插入逗号并序列化该字典。这使您的 JSON 文件有效。

    也许你考虑过这个案例?

    import os
    import json
    
    my_dict = {}
    file_name = "data.json"
    
    
    def update_dict():
        #update your dictionary here
        my_dict["..."] = ...
    
    
    if __name__ == "__main__":
        with open(file_name, 'wb+') as file:
            file.write('[]'.encode('utf-8'))
    
            i = 0
    
            #do it N times just for testing
    
            while i < 10:
                update_dict()
                file.seek(-1, os.SEEK_END)
                file.truncate()
                json_str = json.dumps(my_dict)
                file.write(json_str.encode('utf-8'))
                file.write(',]'.encode('utf-8'))
                i += 1
    
            file.seek(-2, os.SEEK_END)
            file.truncate()
            file.write(']'.encode('utf-8'))
            file.close()
    

    【讨论】:

    • jmkmay 的回答很有帮助。我现在需要一种方法将连接的对象转换为有效的 json 代码,以便我可以遍历它们(我对此完全陌生,所以如果这甚至不可能,请告诉我)。开头的“[]”到底是什么意思?你能在代码的上下文中告诉我这个吗?谢谢!
    • @george 我添加了您要求的上下文
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-07
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 1970-01-01
    • 2011-08-23
    相关资源
    最近更新 更多