【问题标题】:How to add a new dictionary on my JSON list如何在我的 JSON 列表中添加新字典
【发布时间】:2020-04-08 12:16:19
【问题描述】:

所以我有一个基本的user.json 文件。

我的问题是:如何将另一个字典添加到我的 JSON 列表中?

下面是我的代码,如您所见,我尝试了这个:appendupdateinsert,但我找不到任何工作结果。目标是能够添加一个新的:

NAME: name1 // COUNTRY: coutry1 // GENDER: gender1... 到人员 JSON 列表...谢谢。 Python 代码

import json

with open("user.json") as f:
    data = json.load(f)


new_dict = {"name": "name1",
            "Country": "Country2",
            "Gender": "Gender3"}


for person in data["person"]:
    person.update(new_dict)

with open("user.json", "w") as f:
            json.dump(data, f, indent=2)

user.json

{
  "person": [
    {
      "name": "Peter",
      "Country": "Montreal",
      "Gender": "Male"
    },
    {
      "name": "Alex",
      "Country": "Laval",
      "Gender": "Male"
    },
    {
      "name": "Annie",
      "Country": "Quebec",
      "Gender": "Female"
    },
    {
      "name": "Denise",
      "Country": "Levis",
      "Gender": "Female"
    }
  ]
}

【问题讨论】:

    标签: python json list dictionary append


    【解决方案1】:

    如果您想将另一个人员对象添加到人员列表中,您所要做的就是将新对象附加到对象数组中。您不需要遍历 person 对象。请检查我下面的代码是否对您有帮助:

    with open("user.json") as f:
        data = json.load(f)
    
    
    new_dict = {"name": "name1",
                 "Country": "Country2",
                 "Gender": "Gender3"}
    
    data["person"].append(new_dict)
    
    with open("user.json", "w") as f:
        json.dump(data, f, indent=2)
    

    person.update(new_dict) 的python 代码中,您正在更改已经存在的条目person,这不会添加新条目。

    【讨论】:

      猜你喜欢
      • 2022-01-11
      • 2013-09-28
      • 2016-10-29
      • 2020-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多