You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何过滤API返回JSON中的错误记录,获取有效报告的最新下载链接

解决方法

你可以通过列表推导式先过滤有效记录,再按完成时间倒序排序即可实现需求,修正后的代码如下:

import requests

# 你的原始JSON数据
json_obj = {'entries': [{'download_url': 'https://www.google.com', 'id': '4d82cc91-be1e-4d79-a9c9-b9695fc9bfc0', 'format': 'csv', 'created_at': '2021-09-03T15:15:30.059Z', 'completed_at': '2021-09-03T15:15:30.140Z', 'params': {'format': 'csv', 'domain': 'X'}, 'title': 'Y', 'report_type': 'issues-csv'}, {'download_url': 'https://www.cnn.com', 'id': 'f2c620fb-1064-4baf-98f9-e805f48164b0', 'format': 'csv', 'created_at': '2021-09-03T15:07:10.358Z', 'completed_at': '2021-09-03T15:07:10.441Z', 'params': {'format': 'csv', 'domain': 'X'}, 'title': 'Y', 'report_type': 'issues-csv'}, {'download_url': 'https://www.nbc.com', 'id': '9ed29931-3d34-4db9-8e0a-812687785d9e', 'format': 'csv', 'created_at': '2021-09-03T15:03:20.597Z', 'completed_at': '2021-09-03T15:03:20.664Z', 'params': {'format': 'csv', 'domain': 'X'}, 'title': 'Y', 'report_type': 'issues-csv'},{'error': {'message': 'http error 500: Internal Server Error'}, 'id': 'b49dcf8d-e61f-4366-925d-71d18f249b5e', 'format': 'csv', 'created_at': '2021-09-02T12:34:03.930Z', 'completed_at': '2021-09-02T17:55:11.468Z', 'params': {'format': 'csv', 'domain': 'X'}, 'title': 'Y', 'report_type': 'issues-csv'}, {'error': {'message': 'http error 500: Internal Server Error'}, 'id': 'cf92e76e-528e-4209-b7a9-899861184c64', 'format': 'csv', 'created_at': '2021-09-02T12:24:01.591Z', 'completed_at': '2021-09-02T17:56:28.577Z', 'params': {'format': 'csv', 'domain': 'X'}, 'title': 'Y', 'report_type': 'issues-csv'}, {'download_url': 'https://www.espn.com', 'id': 'a6f0a733-268c-4fa3-8212-414780b47317', 'format': 'csv', 'created_at': '2021-09-01T12:24:22.540Z', 'completed_at': '2021-09-01T12:24:22.643Z', 'params': {'format': 'csv', 'domain': 'X'}, 'title': 'Y', 'report_type': 'issues-csv'}]}

# 第一步:过滤仅保留带download_url的有效记录
valid_entries = [entry for entry in json_obj['entries'] if 'download_url' in entry]

# 第二步:按完成时间倒序排序,最新的排在最前面
sorted_valid_entries = sorted(valid_entries, key=lambda x: x['completed_at'], reverse=True)

# 拿到最新的有效下载链接
latest_download_url = sorted_valid_entries[0]['download_url']

# 发起请求下载
response3 = requests.request("GET", latest_download_url, headers=headers, verify=False)

代码说明

  • 过滤逻辑直接通过判断条目是否存在download_url字段实现,自动排除所有携带error的无效记录
  • 排序时设置reverse=True,保证最新生成的报告排在列表首位,直接取第一个元素即可获得你需要的最新有效下载链接
  • 修正了原代码中循环重复赋值url2最终只能拿到最后一个链接的问题

内容的提问来源于stack exchange,提问作者jtooke

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 09:36:04