b
{u'message': {u'method': u'XXXX',
u'params': {u'documentURL': u'xxxx',
u'A': u'yyyy',
u'initialPriority': u'Medium',
u'method': u'GET',
u'mixedContentType': u'none',
u'url': u'xxxx'},
u'date': u'qqqq',
u'time': u'wwww',
u'type': u'Other',
u'wallTime': u'uuuu'},
u'webview': u'0'}
我试图将一个非常大的字典中的几个字段解析为 csv。以下是我尝试过的,
result = []
for i, val in enumerate(b):
output['a']= b[i]['message']['params']['A']
output['date'] = b[i]['message']['date']
output['time'] = b[i]['message']['time']
output['passed'] = b[i]['message']['action']['output']['passed']
result.append(output)
x = pd.DataFrame(json_normalize(result))
x.to_csv('output.csv', encoding='utf-8')
这里的问题是字典的结构不正确,并且有一些时间变量,例如passed (b[i]['message']['action']['output']['passed'])
不存在,因此会出现错误。如何使此代码仅在值存在时追加,如果值不存在则将其设为 NULL?
我只想在该字段存在时进行解析,如果不存在,则希望将其设置为 NULL。有人可以帮我做到这一点吗?
还有更有效的方法来进行这种解析吗?
最佳答案
这是假设“消息”始终存在,但其他人可能会也可能不会:
result = []
for k in b:
msg=b[k]['message'] # if b is a dictionary of dictionaries
msg=k['message'] # if b is a list of dictionaries
if 'params' in msg:
if 'A' in msg['params']:
output['a']=msg['params']['A']
else:
output['a']="NULL"
else:
output['a']="NULL"
if 'date' in msg:
output['date']=msg['date']
else:
output['date']="NULL"
if 'time' in msg:
output['time']=msg['time']
else:
output['time']="NULL"
if 'action' in msg:
if 'output' in msg['action']:
if 'passed' in msg['actions']['output']:
output['passed']=msg['actions']['output']['passed']
else:
output['passed']="NULL"
else:
output['passed']="NULL"
else:
output['passed']="NULL"
result.append(output)
x = pd.DataFrame(json_normalize(result))
x.to_csv('output.csv', encoding='utf-8')
此方法无法扩展,但如果您只需从字典中获取几个字段,则可以使用。
关于python - 将字典中的一些字段解析为 CSV 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38151225/