Python处理赛马API JSON数据:适配退赛马匹格式问题
解决赛马API数据采集中兼容Starter与Scratched马匹的问题
修改后的健壮性代码示例
def collect_horse_data(horse_json): # 初始化基础信息,同时保留原始完整数据确保退赛马匹信息不丢失 horse_info = { 'name': horse_json['name'], 'status': horse_json['status'], 'raw_full_data': horse_json, 'trainer': horse_json.get('trainer', 'Unknown'), 'jockey': horse_json.get('jockey', 'Unknown') } # 安全获取prices数组,避免KeyError或空数组报错 prices = horse_json.get('prices', []) # 分状态处理价格字段 if horse_info['status'] == 'Starter': # Starter状态下按原有逻辑提取,但增加长度校验防止索引越界 horse_info['win_price'] = prices[0]['value'] if len(prices) > 0 else None horse_info['place_price'] = prices[1]['value'] if len(prices) > 1 else None elif horse_info['status'] == 'Scratched': # 退赛马匹直接保留prices原结构,或根据API实际返回提取特定字段 # 示例:如果退赛prices包含取消原因,可针对性提取 for price_entry in prices: if price_entry.get('type') == 'scratch': horse_info['scratch_reason'] = price_entry.get('reason', 'Unspecified') horse_info['scratch_prices'] = prices return horse_info
关键修改说明
- 保留完整原始数据:新增
raw_full_data字段直接存储原始JSON,确保退赛马匹的所有信息(包括特殊结构的prices)都不会丢失,后续有需求可直接从该字段提取。 - 安全的数组与字段访问:
- 用
horse_json.get('prices', [])替代直接索引horse_json['prices'],避免KeyError,同时默认空数组防止后续索引报错。 - 所有可选字段(如trainer、jockey)使用
get()方法并设置默认值,增强代码容错性。
- 用
- 分状态处理逻辑:
- Starter状态下增加数组长度校验(
len(prices) > 0),避免因prices长度不足触发IndexError。 - Scratched状态下根据API实际返回的prices结构处理:如果是特殊标记(如退赛原因)则提取对应字段,否则直接保留原prices数组。
- Starter状态下增加数组长度校验(
- 可选异常防护:如果API返回结构不稳定,可给Starter状态的价格提取添加异常捕获,进一步增强健壮性:
try: horse_info['win_price'] = prices[0]['value'] except (IndexError, KeyError): horse_info['win_price'] = None
内容的提问来源于stack exchange,提问作者DrewS
相关产品推荐
相关产品推荐

