我在 MongoDB 集合中有一組 JSON,它們由 webhooks 接收,我無(wú)法控制它,并且一組元素與另一組元素不同。我能夠檢索那些對(duì)所有其他數(shù)據(jù)具有相同鍵的元素。但我需要檢索這些數(shù)據(jù),無(wú)論它是否存在于其他文檔中。附上 MongoDB 中存在的值的圖片。我正在使用下面的代碼將 webhooks 插入到 MongoDB@app.route('/webhook', methods=['POST', 'GET'])def respond(): collection10 = db['webhooks'] a = request.get_json() print(a) collection10.insert_many(a) return render_template("signin.html")假設(shè)我嘗試檢索“_id”,我可以輕松檢索,因?yàn)閮蓚€(gè)數(shù)據(jù)都有“_id”。但是,如果我嘗試檢索那些存在于一個(gè)元素中而不存在于另一個(gè)元素中的元素,則會(huì)出現(xiàn)錯(cuò)誤。我正在使用此代碼來(lái)檢索元素:@app.route('/webhookdisplay', methods=['POST', 'GET'])def webhooksdis(): collection10 = db['webhooks'] for i in collection10.find({}): posts = i['name'] print(posts) return render_template("webhooks.html", posts = posts)對(duì)于上面的代碼,我得到錯(cuò)誤鍵錯(cuò)誤:'名稱'如果我以與上述相同的方式檢索“_id”,它將被檢索。預(yù)期結(jié)果:我需要檢索嵌套數(shù)據(jù),無(wú)論它是否存在于其他數(shù)據(jù)中。如果有任何其他方法可以在 HTML 頁(yè)面中以表格形式顯示特定數(shù)據(jù),那就太好了目的一旦獲得個(gè)人數(shù)據(jù),我就可以使用 Jinja 以表格形式在前端呈現(xiàn)相同的數(shù)據(jù)
1 回答

aluckdog
TA貢獻(xiàn)1847條經(jīng)驗(yàn) 獲得超7個(gè)贊
如果您不確定返回的記錄是否包含特定鍵,那么您應(yīng)該使用內(nèi)置.get()
函數(shù)。如果鍵不存在,默認(rèn)情況下返回 None ,這與使用方括號(hào)引用不同。這將避免您看到的 KeyError 異常。
posts = i.get('name')
if posts is None:
? ? # Handle logic if name doesn't exist
編輯:如果您需要嵌套字段:
name = i.get('data', {}).get('geofence_metadata', {}).get('name')
添加回答
舉報(bào)
0/150
提交
取消