【问题标题】:How can i insert new json object to existing json file (in the middle of object)如何将新的 json 对象插入现有的 json 文件(在对象中间)
【发布时间】:2023-03-05 09:15:01
【问题描述】:

文件json.json

{"Fiksi":[
    {
    "judul":"fiksi1",
    "pengarang":"pengarang1",
    "file":"namafiksi1.txt"
    },
    {
    "judul":"fiksi2",
    "pengarang":"pengarang2",
    "file":"namafiksi2.txt"
    }
],
"Non-Fiksi":[
    {
    "judul":"nonfiksi1",
    "penulis":"penulis1",
    "file":"namanonfiksi1.txt"
    },
    {
    "judul":"nonfiksi2",
    "penulis":"penulis2",
    "file":"namanonfiksi2.txt"
    }
]

我想在标签“Fiksi”上插入新对象。因此该项目可以插入到文件 json 的中间。 像这样的对象:

item = {"judul":"fiksi3", "pengarang":"pengarang3","file":"namafiksi3.txt"}

我现在的代码:

config = json.loads(open('filejson.json').read())
with open('filejson.json','a') as f:
    data = f["Fiksi"].append(item)
    json.dumps(data)

它不工作

【问题讨论】:

    标签: python json append


    【解决方案1】:

    第一步:读取数据

    config = json.loads(open('filejson.json').read())
    

    Step2:更新数据(在python对象中)

    config["Fiksi"].append(item)
    

    Step3:将所有数据(不追加)写回文件

    with open('filejson.json','w') as f:
        f.write(json.dumps(config))
    

    附带说明一下,在处理文件时,您可以使用json.loadjson.dump 代替json.loadsjson.dumps,所以它会是

    with open('filejson.json', 'r') as f:
        config = json.load(f)
    config["Fiksi"].append(item)
    with open('filejson.json','w') as f:
        json.dump(config, f)
    

    【讨论】:

      【解决方案2】:

      最好的方法是使用 python 对象:

      • 导入json
      • 使用 json.load 加载文件
      • 在加载的字典中插入
      • 使用 json.dump 转储到文件

      【讨论】:

        【解决方案3】:

        只需添加:

        f.write(json.dumps(data))
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-01-09
          • 1970-01-01
          • 1970-01-01
          • 2019-12-04
          • 1970-01-01
          • 2021-11-12
          相关资源
          最近更新 更多