我在從mongodb將數據導出到csv時,遇到python腳本中缺少字段名稱的問題。類型字段名稱存在於第一條記錄中,但它不會出現在其餘記錄中。如果編寫python腳本,如果它不存在,則爲類型字段提供空值。從mongodb導出json數據到csv
的MongoDB集合的樣本:
"stages": [
{
"interview": false,
"hmNotification": false,
"hmStage": false,
"type": "new",
"isEditable": false,
"order": 0,
"name": {
"en": "New"
},
"stageId": "51d1a2f4c0d9887b214f3694"
},
{
"interview": false,
"hmNotification": true,
"isEditable": true,
"order": 1,
"hmStage": true,
"name": {
"en": "Pre-Screen"
},
"stageId": "51f0078d7297363f62059699"
},
{
"interview": false,
"hmNotification": false,
"hmStage": false,
"isEditable": true,
"order": 2,
"name": {
"en": "Phone Screen"
},
"stageId": "51d1a326c0d9887721778eae"
}]
Python腳本的示例:
import csv
cursor = db.workflows.find({}, {'_id': 1, 'stages.interview': 1, 'stages.hmNotification': 1, 'stages.hmStage': 1, 'stages.type':1, 'stages.isEditable':1, 'stages.order':1,
'stages.name':1, 'stages.stageId':1 })
flattened_records = []
for stages_record in cursor:
stages_record_id = stages_record['_id']
for stage_record in stages_record['stages']:
flattened_record = {
'_id': stages_record_id,
'stages.interview': stage_record['interview'],
'stages.hmNotification': stage_record['hmNotification'],
'stages.hmStage': stage_record['hmStage'],
'stages.type': stage_record['type'],
'stages.isEditable': stage_record['isEditable'],
'stages.order': stage_record['order'],
'stages.name': stage_record['name'],
'stages.stageId': stage_record['stageId']}
flattened_records.append(flattened_record)
運行python腳本時,它顯示KeyError異常: 「類型」。請幫助我如何在腳本中添加缺少的字段名稱。
它工作時,增加了「stages.typ非常好‘:stage_record.get。在python腳本(’類型」)類型的值出現在CSV文件。非常感謝。 – user7070824
感謝您的幫助。如何刪除u字母,括號和Python中子字段的名稱?謝謝。 – user7070824