使用python解析JSON文件

使用python解析JSON文件,python,json,parsing,python-3.x,Python,Json,Parsing,Python 3.x,我需要一个使用python解析json文件的帮助。这是我的示例json文件 我试过下面的代码,但是如果任何属性值为null,itz就会抛出一个键错误, 如何跳过这些属性并继续解析剩余数据 import csv with open("global.json") as file: data = json.load(file) with open("single.csv", "w") as file: csv_file = csv.writer(file) csv_file.writerow

我需要一个使用python解析json文件的帮助。这是我的示例json文件

我试过下面的代码,但是如果任何属性值为null,itz就会抛出一个键错误, 如何跳过这些属性并继续解析剩余数据

import csv

with open("global.json") as file:
data = json.load(file)

with open("single.csv", "w") as file:
csv_file = csv.writer(file)
csv_file.writerow 

for item in data:
    csv_file.writerow([item['policyNumber'],
                       item['policyType'],
                       item['policyStatus'],
                       item['termEffectiveDate'],
                       item['sourceSystem'],
                       item['agency'],
                       item['policyAddress'][0]['address1'],
                       item['policyAddress'][0]['zipCode'],
                       item['policyAddress'][0]['city'],
                       item['policyAddress'][0]['state'],
                       item['consumers'][0]['matchFlag'],
                       item['consumers'][0]['firstName'],
                       item['consumers'][0]['lastName'],
                       item['consumers'][0]['eid'],
如果未定义键,请使用获取默认值:

item.get('policyNumber', ''),
也许:

item.get('policyAddress', [{}])[0].get('zipCode', ''),
# ...
item.get('consumers', [{}])[0].get('matchFlag', ''),
默认为嵌套列表项的空字典。如果存在
策略地址
消费者
键,但值为空列表,则后者仍可能失败

您可以稍微预处理每个项目:

for item in data:
    if not item.get('policyAddress'):
        item['policyAddress'] = [{'address1': '', 'zipCode': '', 'city': '', 'state': ''})
    if not item.get('consumers'):
        item['consumers'] = [{'matchFlag': '', 'firstName': '', 'lastName': '', 'eid': ''})
然后使用:

item['policyAddress'][0].get('address1', '')

等等。

谢谢Martijn将尝试此功能…因此对于例如:item['policyAddress'][0]['zipCode'],应替换为item.get('policyAddress','','zipCode','')@user3514648:no;您将使用
item.get('policyAddress',[{}])[0].get('zipCode','')
;这将返回
[{}]
(一个包含一个空字典的列表)作为
policyAddress
的默认值,然后如果结果没有
zipCode
键,则返回一个空字符串。Martijn Pieters提供的答案是一个很好的答案。如果我理解你想做什么,你想把JSON转换成csv,这个问题已经得到了回答。