python - 更新 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 文件中的数据,或者如何避免插入已经存在的数据?
解决方案
推荐阅读
- reactjs - 简单的反应路线没有出现
- java - 在字符串中分组字符的更简洁的方法
- node.js - 无法解决依赖关系:来自 codelyzer@5.2.2 的 peer tslint@"^5.0.0 || ^6.0.0" node_modules/codelyzer dev codelyzer@"^5.1.2" 来自根项目
- python - Google Colab 中的 blpapi 抛出 InvalidArgumentException
- sql - 按月获取错误过滤记录SQL
- javascript - 如何在axios中传递url路径变量
- powershell - 找不到接受参数“=”错误的位置参数
- ffmpeg - 如何组合这些 FFMPEG 命令?
- google-apps-script - 当我点击通过 webapp 发送时,如何显示确认通知?
- swift - 将 RGBA32Float MTLTextures 转换为 NSImage