Search code examples
pythonfinance

Need a blank value returned if there is no path within JSON file (Python)


I am using a function to cycle through a list of funds using APIs. Sometimes the JSON files differ and the path is different or doesn't exist. How do I return a blank value if there is no path and then continue to the next fund in my list:

(Only Test API Key)

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)

Solution

  • Use the dictionary 'get()' methods instead of the square brackets.

    ltpg = data['ETF_Data'].get('Valuations_Growth', {}).get('Growth_Rates_Portfolio', {}).get('Long-Term Projected Earnings Growth', [])
    

    The second parameter is the value returned if the key isn't found. Passing an empty dict there allows you to chain them together.