我正在使用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
。并应打印所有数据。在
我尝试在代码中使用try:and except KeyError:进行了更多搜索,并能够将JSON数据插入到SQL表中,没有任何错误。在
如果您向我们展示数据或解释其用途,我们可能会提供更好的答案,但现在如果您希望在不获取异常的情况下运行此代码,则需要考虑到并非所有项都包含此键的可能性。一种方法是使用},如果
get()
调用而不是__getitem__
调用(使用方括号)dict.get(key, default)
方法返回{key
不在dict
中,None
如果不提供default
。因此,一个基本的解决方案是:一个稍微好一点的版本,它可以告诉您缺少哪个密钥:
^{pr2}$相关问题 更多 >
编程相关推荐