python - 将字典中的一些字段解析为 CSV 时出错

标签 python csv parsing pandas dictionary

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/

相关文章:

python - yaml 锚定义在 PyYAML 中加载

python - 在 Beautiful Soup 中向 p 标签添加文本

python - 在 python 中直接写入 .csv 时,如何防止用户输入相同的输入两次

javascript - 显示价格时值(value)中的逗号不起作用

python - 修复无效的 JSON 八进制转义

java - csv-commons - withSkipHeaderRecord 选项不会跳过任何内容

python - python numba中非常大的整数

python - 如何在 GtkTextView 中插入 UTF8 文字?

python - 解析 Pandas 中的大字符串值

php - 我如何在 php 中组织可下载的 csv 文件