使用Python访问ActiveCollab REST API返回嵌套JSON的value值报错如何解决
错误原因
- 不必要的Response对象强转:
requests.get()返回的是原生Response对象,无需转dict即可直接读取.text属性,强制转换属于多余操作,可能引发不可预期的结构异常。 - 遍历对象错误:
json.loads(a.text)得到的是包含time_records键的顶层字典,直接遍历字典时返回的是键名(字符串类型),对字符串使用['time_records']索引自然触发类型错误。
修正后的完整代码
import requests import json startdate = "2021-08-01" enddate = "2021-08-31" fromto = f"?from={startdate}&to={enddate}" def ac_rq(endpoint): token = '*' url = f"https://*/api/v1/{endpoint}" # 直接返回Response对象即可,不需要转dict resp = requests.get(url, headers={'X-Angie-AuthApiToken': token}) return resp a = ac_rq(f'projects/129/time-records/filtered-by-date{fromto}') b = json.loads(a.text) # 直接遍历time_records数组即可 for record in b.get('time_records', []): print(record['value']) input("press enter to exit")
额外优化提示
- 可以直接用
Response对象的.json()方法替代json.loads(a.text),写法更简洁:b = a.json() - 用
get('time_records', [])做兼容处理,避免接口返回结构异常时触发键不存在的报错。
内容的提问来源于stack exchange,提问作者Luke
相关产品推荐
相关产品推荐

