简体   繁体   English

Python 上的 JSONDecode 错误 [Errno 预期值] 稍后重试:0/预期值:第 1 行第 1 列(字符 0)

[英]JSONDecode Error on Python [Errno Expecting value] Retry later : 0/Expecting value: line 1 column 1 (char 0)

When I plug in the get request for a smaller subset of the data, it works fine.当我插入获取较小数据子集的请求时,它工作正常。 But the larger for loop I'm using seems to break the code somehow.但是我使用的更大的 for 循环似乎以某种方式破坏了代码。 Is the API limiting the amount of data I can take out? API 是否限制了我可以取出的数据量? The loop works for a little bit until it suddenly crashes, every time I run it it crashes at a different point.循环工作了一点点,直到它突然崩溃,每次我运行它时,它都会在不同的点崩溃。 I'd rather not have to make 30 dataframes and merge them all instead of just creating one from this loop.我宁愿不必制作 30 个数据帧并将它们全部合并,而不仅仅是从这个循环中创建一个。

Here's the code:这是代码:

players_stats=[]

seasons=[1990,1991,1992,1993,1994,1995,1996,1997,1998,1999,2000,
       2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,
       2012,2013,2014,2015,2016,2017,2018,2019,2020,2021]

players_game_stats_url="https://www.balldontlie.io/api/v1/season_averages?"
print("Retrieving Player Ids")
print("-"*20)

for season in seasons:
    for player_id in players_ids:
        try:
            player_game_stats=requests.get(players_game_stats_url, params={"season":season,"player_ids[]":player_id}).json()
            player_average_pts=player_game_stats['data'][0]['pts']
            player_avg_assists=player_game_stats['data'][0]['ast']
            player_avg_blocks=player_game_stats['data'][0]['blk']
            player_avg_defrebounds=player_game_stats['data'][0]['dreb']
            player_avg_offrebounds=player_game_stats['data'][0]['reb']
            player_avg_3pt_attempts=player_game_stats['data'][0]['fg3a']
            player_avg_3pt_made=player_game_stats['data'][0]['fg3m']
            player_avg_2pt_attempts=player_game_stats['data'][0]['fga']
            player_avg_2pt_made=player_game_stats['data'][0]['fgm']
            player_avg_ft_attempts=player_game_stats['data'][0]['fta']
            player_avg_ft_made=player_game_stats['data'][0]['ftm']
            player_avg_steals=player_game_stats['data'][0]['stl']
            player_avg_mins=player_game_stats['data'][0]['min']
            player_avg_turnovers=player_game_stats['data'][0]['turnover']
            
            players_stats.append({"Player ID": player_id,"Season":season,"Average Points": player_average_pts,
                                  "Average Assists": player_avg_assists, "Average Blocks":player_avg_blocks, 
                                  "Average Defensive Rebounds":player_avg_defrebounds, 
                                  "Average Offensive Rebounds":player_avg_offrebounds, 
                                  "Average 3PT Attempts":player_avg_3pt_attempts,
                                 "Average 3PT Made":player_avg_3pt_made, "Average 2PT Attempts":player_avg_2pt_made,
                                  "Average 2PT Made":player_avg_2pt_made,
                                 "Average Free Throw Attempts":player_avg_ft_attempts, 
                                  "Average Free Throws Made":player_avg_ft_made, "Average Steals per Game":player_avg_steals,
                                 "Average Mins per Game":player_avg_mins,"Average Turn Overs per Game":player_avg_turnovers })

        except (IndexError):
            print(f"The stats for player:{player_id} were not found for season:{season}")
            pass
        
players_stats

A simpler version of it, which only includes one year (season=1990), works fine and gives the desired output:它的一个更简单的版本,只包括一年 (season=1990),工作正常并给出所需的 output:

Retrieving Player Ids
--------------------
The stats for player:671 were not found for 1990
The stats for player:735 were not found for 1990
The stats for player:847 were not found for 1990
The stats for player:907 were not found for 1990
The stats for player:957 were not found for 1990
The stats for player:1037 were not found for 1990
The stats for player:1089 were not found for 1990
The stats for player:1179 were not found for 1990
The stats for player:1247 were not found for 1990
The stats for player:1281 were not found for 1990
The stats for player:1368 were not found for 1990
The stats for player:1445 were not found for 1990
The stats for player:237 were not found for 1990
The stats for player:220 were not found for 1990
The stats for player:1593 were not found for 1990
[{'Player ID': 2895,
  'Average Points': 18.43,
  'Average Assists': 2.2,
  'Average Blocks': 1.34,
  'Average Defensive Rebounds': 6.62,
  'Average Offensive Rebounds': 10.26,
  'Average 3PT Attempts': 0.51,
  'Average 3PT Made': 0.18,
  'Average 2PT Attempts': 6.95,
  'Average 2PT Made': 6.95,
  'Average Free Throw Attempts': 5.97,
  'Average Free Throws Made': 4.36,
  'Average Steals per Game': 0.96,
  'Average Mins per Game': '35:09',
  'Average Turn Overs per Game': 2.93}]

But the code that loops through all of the years ends up like this inevitably:但是循环遍历所有年的代码不可避免地最终是这样的:

Retrieving Player Ids
--------------------
The stats for player:671 were not found for season:1990
The stats for player:735 were not found for season:1990
The stats for player:847 were not found for season:1990
---------------------------------------------------------------------------
JSONDecodeError                           Traceback (most recent call last)
File ~\anaconda3\lib\site-packages\requests\models.py:910, in Response.json(self, **kwargs)
    909 try:
--> 910     return complexjson.loads(self.text, **kwargs)
    911 except JSONDecodeError as e:
    912     # Catch JSON-related errors and raise as requests.JSONDecodeError
    913     # This aliases json.JSONDecodeError and simplejson.JSONDecodeError

File ~\anaconda3\lib\json\__init__.py:346, in loads(s, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    343 if (cls is None and object_hook is None and
    344         parse_int is None and parse_float is None and
    345         parse_constant is None and object_pairs_hook is None and not kw):
--> 346     return _default_decoder.decode(s)
    347 if cls is None:

File ~\anaconda3\lib\json\decoder.py:337, in JSONDecoder.decode(self, s, _w)
    333 """Return the Python representation of ``s`` (a ``str`` instance
    334 containing a JSON document).
    335 
    336 """
--> 337 obj, end = self.raw_decode(s, idx=_w(s, 0).end())
    338 end = _w(s, end).end()

File ~\anaconda3\lib\json\decoder.py:355, in JSONDecoder.raw_decode(self, s, idx)
    354 except StopIteration as err:
--> 355     raise JSONDecodeError("Expecting value", s, err.value) from None
    356 return obj, end

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

During handling of the above exception, another exception occurred:

JSONDecodeError                           Traceback (most recent call last)
Input In [8], in <cell line: 11>()
     12 for player_id in players_ids:
     13     try:
---> 14         player_game_stats=requests.get(players_game_stats_url, params={"season":season,"player_ids[]":player_id}).json()
     15         player_average_pts=player_game_stats['data'][0]['pts']
     16         player_avg_assists=player_game_stats['data'][0]['ast']

File ~\anaconda3\lib\site-packages\requests\models.py:917, in Response.json(self, **kwargs)
    915     raise RequestsJSONDecodeError(e.message)
    916 else:
--> 917     raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)

JSONDecodeError: [Errno Expecting value] Retry later
: 0

As you can see it only gets to a few loops before producing an error code.如您所见,在生成错误代码之前,它只进行了几次循环。 Any advice for an amateur python user?对业余 python 用户有什么建议吗?

The API server was throttling my code. API 服务器正在限制我的代码。 Adding a sleep function to it helped overcome that issue.添加 sleep function 有助于解决这个问题。 import time + sleep function for the win!输入时间+睡眠 function 为胜利!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM