如果 JSON 文件 (Python) 中没有路径,则需要返回空白值
Need a blank value returned if there is no path within JSON file (Python)
我正在使用一个函数来循环使用 APIs 的基金列表。有时 JSON 文件不同,路径不同或不存在。如果没有路径,我如何 return 一个空白值,然后继续我列表中的下一个基金:
(仅测试 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', [])
第二个参数是未找到密钥时返回的值。在那里传递一个空的字典可以让你把它们链接在一起。
我正在使用一个函数来循环使用 APIs 的基金列表。有时 JSON 文件不同,路径不同或不存在。如果没有路径,我如何 return 一个空白值,然后继续我列表中的下一个基金:
(仅测试 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', [])
第二个参数是未找到密钥时返回的值。在那里传递一个空的字典可以让你把它们链接在一起。