簡體   English   中英

Python:將新字典附加到 json 文件

[英]Python: append new dictionary to json file

我在下面有一個現有的 json 文件,我想將新字典附加到 json 文件中。

{
    "company_id": 1,
    "company_name": "Google"
    "members": [
        {
            "name": "John",
            "title": "Analyst",
            "age": "24",
        },
        {
            "name": "Dave",
            "title": "Developer",
            "age": "27",

        },
        {
            "name": "Jim",
            "title": "Manager",
            "age": "34",

        }
    ]
}

我努力了

        file_data = json.load(file)
        file_data.update(new_data)
        file.seek(0)
        json.dump(file_data, file, indent=4)

編輯:

新數據如下,字典類型

new_data = {
    "company_id": 1,
    "company_name": "Google",
    "members": [
        {
            "name": "James",
            "title": "CEO",
            "age": "50"
        }
    ]
}

它將新數據添加到文件中,但會弄亂現有數據。 這是輸出。

{
    "company_id": 1,
    "company_name": "Google",
    "members": [
        {
            "name": "John",
            "title": "Analyst",
            "age": "24"
        },
        {
            "name": "Dave",
            "title": "Developer",
            "age": "27"
        },
        {
            "name": "Jim",
            "title": "Manager",
            "age": "34"
        }
    ]
}{
    "company_id": 1,
    "company_name": "Google",
    "members": [
        {
            "name": "James",
            "title": "CEO",
            "age": "50"
        }
    ]
}

我希望將同一 company_id 中的新成員添加到成員中,但它只是在現有成員之后創建另一個 json。

我認為您需要在轉儲更新的數據之前關閉 json 文件:

with open("data.json", "r") as f:
    data = json.load(f)
    data.update(your_data)

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

更新答案

可能您需要直接引用需要添加新數據的位置:

import json

new_data = {
    "company_id": 1,
    "company_name": "Google",
    "members": [
        {
            "name": "James",
            "title": "CEO",
            "age": "50"
        }
    ]
}

with open("data1.json", "r") as f:
    data = json.load(f)
    data['members'] += new_data['members'] # <-- here

with open("data1.json", "w") as f:
    json.dump(data, f)

只有當新數據比舊數據長時, file.seek(0)才能重寫打開的文件。 如果新數據更短,你會變得一團糟。

看起來您應該附加新成員:

file_data[‘members’] += new_data[‘members’]

而不是進行更新。

試試這個代碼,它對我有用:

your_data = {"d": 4}
with open("file.json", "r+") as file:
    data = json.load(file)
    data.update(your_data)
    file.seek(0)
    json.dump(data, file, indent=4)

試試這個

file_data.append(your_data)

假設您僅嘗試添加 1,這應該向 json 添加 1 dict

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM