【问题标题】:How to add new dictionary into existed json file with dictionary?如何使用字典将新字典添加到现有的 json 文件中?
【发布时间】:2018-05-31 14:15:53
【问题描述】:

我有一个json文件保存在本地服务器,如:

    {
      "user": "user1",
      "id": "21779"
    } 

我想在这个 json 文件中写入另一个字典,我需要这样的新内容:

    {
       {
         "user": "user1",
         "id": "21779"
       },
       {
         "user": "user2",
         "id": "21780"
       }
     }

或者:

     [
       {
         "user": "user1",
         "id": "21779"
       },
       {
         "user": "user2",
         "id": "21780"
       }
     ]

我尝试使用 json.dump() 添加新元素,但显示为:

    {
      "user": "user1",
      "id": "21779"
    }
    {
      "user": "user2",
      "id": "21780"
    }

这不是一个有效的 json 文件。

如何使用 json.dump、json.load 或其他方法? 谢谢你的帮助!

【问题讨论】:

  • 第二个条件可以通过list来实现。使用list.append()

标签: python json list dictionary


【解决方案1】:

您必须阅读您的JSON 文件,然后将其转换为list 而不是dict。然后,您只需附加到该列表并覆盖您的 JSON 文件。

import json

data = json.load(open('data.json'))

# convert data to list if not
if type(data) is dict:
    data = [data]

# append new item to data lit
data.append({
  "user": "user2",
  "id": "21780"
})

# write list to file
with open('data.json', 'w') as outfile:
    json.dump(data, outfile)

【讨论】:

    【解决方案2】:

    您可以使用列表而不是 dict ,如果有帮助,请尝试以下一种解决方案

    import json
    
    def appendList():
        with open("test.json", mode='r', encoding='utf-8') as f:
            feeds = json.load(f)
            print(feeds)
    
        with open("test.json", mode='w', encoding='utf-8') as feedsjson:
            entry = { "user": "user3","id": "21574"}
            feeds.append(entry)
            print(json.dump(feeds, feedsjson))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-21
      • 2022-01-11
      • 2017-12-17
      • 2015-05-01
      • 2020-11-20
      • 2021-05-17
      相关资源
      最近更新 更多