使用python从API获取JSON数据时获取keyerror

2024-09-30 12:15:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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'

我的代码:

^{pr2}$

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


Tags: 数据inpyservicelinescripttempnagios
2条回答

我尝试在代码中使用try:and except 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

如果您向我们展示数据或解释其用途,我们可能会提供更好的答案,但现在如果您希望在不获取异常的情况下运行此代码,则需要考虑到并非所有项都包含此键的可能性。一种方法是使用get()调用而不是__getitem__调用(使用方括号)dict.get(key, default)方法返回{},如果key不在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")

一个稍微好一点的版本,它可以告诉您缺少哪个密钥:

^{pr2}$

相关问题 更多 >

    热门问题