我正在使用一个函数,使用API循环浏览一系列资金。有时JSON文件不同,路径不同或不存在。如果没有路径,如何返回空白值,然后继续执行列表中的下一个基金:
((仅测试API密钥)
def EPS (ticker):
url = "https://eodhistoricaldata.com/api/fundamentals/{ticker}.LSE?api_token=OeAFFmMliFG5orCUuwAKQ8l4WWFQ67YX".format(ticker=ticker)
with request.urlopen(url) as response:
source = response.read()
data = json.loads(source)
type(data['ETF_Data']['Valuations_Growth']['Growth_Rates_Portfolio']['Long-Term Projected Earnings Growth'])
len(data['ETF_Data']['Valuations_Growth']['Growth_Rates_Portfolio']['Long-Term Projected Earnings Growth'])
EPS = data['ETF_Data']['Valuations_Growth']['Growth_Rates_Portfolio']['Long-Term Projected Earnings Growth']
return (EPS)
使用字典的'get()'方法而不是方括号。
ltpg = data['ETF_Data'].get('Valuations_Growth', {}).get('Growth_Rates_Portfolio', {}).get('Long-Term Projected Earnings Growth', [])
第二个参数是如果找不到密钥,则返回的值。在此处传递一个空的dict可使您将它们链接在一起。