首页 > 解决方案 > 使用 Json 迭代 API,

问题描述

导入请求导入 json 导入 numpy 作为 np 导入 pandas 作为 pd

url = " https://financialmodelingprep.com/api/v3/financial-statement-growth/PETS " JC = requests.get(url).json()

内容 = json.dumps(JC, 缩进 = 4, sort_keys=True)

日期 = [“宠物”,“APPL”]

日期列表 =[]

对于日期中的日期:JC = requests.get(" https://financialmodelingprep.com/api/v3/financial-statement-growth/ "+ dates).json()

dates_list.append(JC['growth'])

dataset = pd.DataFrame(dates_list) dataset.sample(5)

我得到这个错误:

6 JC = requests.get(" https://financialmodelingprep.com/api/v3/financial-statement-growth/ "+ dates).json() 7 ----> 8中的 KeyError Traceback(最近一次通话最后一次)dates_list.append(JC['growth']) 9 10 数据集 = pd.DataFrame(dates_list)

KeyError:“增长”

标签: pythonjsonpandas

解决方案


import requests 
import json 
import numpy as np 
import pandas as pd

url = "https://financialmodelingprep.com/api/v3/financial-statement-growth/PETS" 
JC = requests.get(url).json()

content = json.dumps(JC, indent = 4, sort_keys=True)

dates = ["PETS", "AAPL", "APPL"]

dates_list =[]

for dates in dates: 

    JC = requests.get("https://financialmodelingprep.com/api/v3/financial-statement-growth/"+ dates).json()
    if JC == {}:
        print "invalid ticker ... "
    else:
        dates_list.append(JC['growth'])


dataset = pd.DataFrame(dates_list)
print dataset

首先,股票代码 APPL 在 SEC 数据库中不存在https://www.sec.gov/cgi-bin/browse-edgar?CIK=APPL&owner=exclude&action=getcompany 然后 api 返回一个没有出现密钥增长的空目录里面。您应该捕获错误,您可以在将值添加到 dates_lists 之前检查字典是否为空

控制台输出

fmp_team:fmp $ python stackoverflow.py 
invalid ticker ... 
                                                  0                                                  1   ...                                                 9                                                  10
0  {u'Weighted Average Shares Diluted Growth': u'...  {u'Weighted Average Shares Diluted Growth': u'...  ...  {u'Weighted Average Shares Diluted Growth': u'...                                               None
1  {u'Weighted Average Shares Diluted Growth': u'...  {u'Weighted Average Shares Diluted Growth': u'...  ...  {u'Weighted Average Shares Diluted Growth': u'...  {u'Weighted Average Shares Diluted Growth': u'...

[2 rows x 11 columns]

推荐阅读