使用python从API提取JSON数据时遇到keyerror

时间:2019-01-11 10:43:52

标签: python json api keyerror

在打印使用python从API提取的json数据之一时,我得到了keyerror的帮助。

错误:

nagios_service之外,我还可以打印其他数据

Traceback (most recent call last):

  File "<ipython-input-55-3a1eadbbe594>", line 1, in <module>
    runfile('Y:/_Temp/MEIPE/python/20190104_Script_Jason_APIv3.py', wdir='Y:/_Temp/MEIPE/python')

  File "C:\Users\MEIPE\AppData\Local\Continuum\anaconda2\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 704, in runfile
    execfile(filename, namespace)

  File "C:\Users\MEIPE\AppData\Local\Continuum\anaconda2\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 93, in execfile
    exec(compile(scripttext, filename, 'exec'), glob, loc)

  File "Y:/_Temp/MEIPE/python/20190104_Script_Jason_APIv3.py", line 68, in <module>
    print data[i]["_source"]["nagios_service"]

KeyError: 'nagios_service'

我的代码:

url1 = "http://nagiosdatagateway.vestas.net/esq/ITE1452552/logstash- 
2018.12.16/2/desc"
response = urllib.urlopen(url1)
data = json.loads(response.read())
#define db connection
cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
                  "Server=DKCDCVDCP42\DPA;"
                  "Database=VPDC;"
                  "Trusted_Connection=yes;")
cursor = cnxn.cursor()
sql="SELECT count(*)  as count_of_rows FROM [VPDC].[pa]. 
[ROC_Nagios_Reporting_RawData]"
cursor.execute(sql)
for row in cursor.fetchall():
    k = row.count_of_rows
i = 0  
j = len(data)#find length of data set
#print j
for i in range(0,j): #loop to insert date into SQL Server
    print data[i]["_source"]["nagios_service"]
    print data[i]["_source"]["nagios_host"]
    print data[i]["_source"]["nagios_author"]
    print data[i]["_source"]["nagios_severity_label"]
    print data[i]["_source"]["nagios_external_command"]
    print data[i]["_source"]["@timestamp"]
 cnxn.commit() #commit transaction
 cursor.close()
 cnxn.close()

我需要帮助在keyerror上修复此nagios_service。并且应该打印所有数据。

2 个答案:

答案 0 :(得分:1)

如果您向我们展示了数据或解释了此目的是什么,我们也许可以提供更好的答案,但是就目前而言,如果您想在不获取异常的情况下运行此代码,则需要考虑所有项目都包含此密钥。一种方法是使用get()调用而不是__getitem__调用(使用方括号)-如果dict.get(key, default)不在{中,则default方法返回key {1}},如果您未提供dict,则为None。因此,一个基本的解决方案是:

default

一个更好的版本,它将告诉您缺少哪个密钥:

for i in range(0,j): #loop to insert date into SQL Server
    source_data = data[i]["_source"]
    print source_data.get("nagios_service")
    print source_data.get("nagios_host")
    print source_data.get("nagios_author")
    print source_data.get("nagios_severity_label")
    print source_data.get("nagios_external_command")
    print source_data.get("@timestamp")

答案 1 :(得分:0)

在搜索了更多代码后,我尝试在代码中使用try:和KeyError:除外,并且能够将JSON数据插入SQL表中而没有任何错误。

url1 = "http://nagiosdatagateway.vestas.net/esq/ITE1452552/logstash-" + ysday1
#print url1 #test
#url = "http://nagiosdatagateway.vestas.net/esq/ITE1452552/logstash- 
2018.12.16/2/desc"
response = urllib.urlopen(url1)
data = json.loads(response.read())

#define db connection
cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
                  "Server=DKCDCVDCP42\DPA;"
                  "Database=VPDC;"
                  "Trusted_Connection=yes;")
cursor = cnxn.cursor()
sql= "SELECT count(*)  as count_of_rows FROM [VPDC].[pa]. 
[ROC_Nagios_Reporting_RawData]"
cursor.execute(sql)
for row in cursor.fetchall():
    k = row.count_of_rows
i = 0  
j = len(data)#find length of data set
#print j

#for each in data:    
for i in range(0,j): #loop to insert date into SQL Server
        try:
            print data[i]["_source"]["nagios_author"]
            print data[i]["_source"]["nagios_service"]
            cursor.execute("insert into [VPDC].[pa].[ROC_Nagios_Reporting_RawData] 
            (Nagios_Author,Nagios_service,Nagios_host,Nagios_comment) values 
            (?,?,?,?)",(data[i]["_source"]["nagios_author"],data[i]["_source"] 
            ["nagios_service"],data[i]["_source"]["nagios_host"],data[i]["_source"] 
            ["nagios_comment"] ))

        except KeyError:
            pass
cnxn.commit() #commit transaction
cursor.close()
cnxn.close() #close connection