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

使用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 17:06:02