首页 > 解决方案 > 更新 JSON 文件时如何检查数据是否退出

问题描述

我同时使用 Python 和 JSON。我的想法是将 python 文件中的新数据插入到 JSON 文件中。确切地说,在我的 python 文件中,我从 firebase 数据库中获取数据,并将其插入到 JSON 文件中,我能够在 JSON 文件中插入新数据而不删除任何数据,我的问题是我没有有任何机制来避免重复数据。

因此,首先是能够从 firebase 获取数据并将该数据插入 JSON 文件的代码:


cred = credentials.Certificate(
    "firebasecredentials.json")
firebase_admin.initialize_app(cred)

db = firestore.client()

# read data
# Getting a Document with a known ID

intents = {"intents": []}

with open('intents.json') as json_file:
    olddata = json.load(json_file)
    for ob in olddata['intents']:
        intents['intents'].append(ob)

print("old data:", len(intents['intents']))
results = db.collection('users').document(
    'Peo5kqpi4GORXehD3oQVRXpHGfD2').collection('chats').get()
for index, result in enumerate(results):
    data = result.to_dict()
    intents["intents"].append({
        "tag": f"firebaseImportantData{index}",
        "patterns":   [data["messageQuestion2"],data["messageQuestion3"],data["messageQuestion4"],data["messageQuestion5"],data["messageQuestion6"],data["messageQuestion7"]],
        "responses": [data["IAmessageQuestion8"]]
    })
print("new data: ", len(intents['intents']))
with open("intents.json", "w") as outfile:
    json.dump(intents, outfile)

这是我的 json 文件的示例:


{
    "intents": [
        {
            "tag": "firebaseImportantData0",
            "patterns": [
                "Hi",
                "Hey",
                "Is anyone there?",
                "Hello",
                "Good day",
                "charlot"
            ],
            "responses": [
                "Hey :-)",
                "Hello",
                "Hi there",
                "Hiya",
                "How are you going?",
                "Whats up!",
                "Long time no see!"
            ]
        }
    ]
}

我已经从数据库中插入了该数据,但是如果我再次运行 python 文件,我将再次获得相同的数据,标记名中带有 +1,如下所示:


{
    "intents": [
        {
            "tag": "firebaseImportantData1",
            "patterns": [
                "Hi",
                "this a new entry"
            ],
            "responses": [
                "Hey :-)",
                "Hello",
                "Hi there",
                "Hiya",
                "How are you going?",
                "Whats up!",
                "Long time no see!"
            ]
        }
    ]
}

正如你所看到的,在模式部分“hi”是重复的,所以我的问题是,我不想要重复的模式项,这就是我想要避免的。

所以,我的问题是,是否有任何方法可以不复制 JSON 文件中的数据,或者如何避免插入已经存在的数据?

标签: pythonjsonfirebase

解决方案


推荐阅读