Python解析API返回的JSON字段时报TypeError错误如何解决
问题修复方案
报错原因
- 错误1:
alertDetails.text是JSON格式的字符串类型,不能直接用字典的键索引取值,必须先反序列化为Python字典对象 - 错误2:不要用
dict作为变量名,会覆盖Python内置的字典类型,引发后续潜在问题 - 错误3:第一个接口返回的告警ID列表本身是JSON格式,直接用
split('","')拆分字符串的方式不稳定,容易拿到带多余符号的错误ID - 错误4:你需要提取的目标URL是
Details.Source.URL,原代码错误提取了Assets下的字段,和需求不符
修复后的完整代码
import requests # UserID + Api Key auth = ('USERID','APIKEY') headers = {'Content-Type': "application/json"} # 获取告警列表接口,直接解析为JSON对象 list_url = "https://api.intsights.com/public/v1/data/alerts/alerts-list?alertType=Phishing" alerts_resp = requests.get(list_url, auth=auth, headers=headers) # 反序列化为Python对象,若接口返回结构有嵌套,可自行调整取值逻辑拿到告警ID列表 alert_id_list = alerts_resp.json() for alert_id in alert_id_list: detail_url = f"https://api.intsights.com/public/v1/data/alerts/get-alert/{alert_id}" detail_resp = requests.get(detail_url, auth=auth, headers=headers) # 把返回的JSON字符串转成字典 alert_detail = detail_resp.json() # 提取目标字段 source_url = alert_detail['Details']['Source']['URL'] found_date = alert_detail['FoundDate'] # 按要求格式输出 print(f"URL: {source_url}") print(f"FoundDate: {found_date}")
额外优化建议
- 可以加异常捕获逻辑,处理接口返回失败、字段缺失的场景,避免程序直接崩溃
- requests库已经封装了
get方法,不需要每次都调用request("GET", ...),写法更简洁
内容的提问来源于stack exchange,提问作者Richard
相关产品推荐
相关产品推荐

