Python中如何获取JSON数组最后一个对象的end_date参数
解决方法
错误原因分析
你的代码存在几个问题:
- 循环遍历整个数组,每次处理单个对象后用
[-1]取end_date字符串的最后一个字符,导致输出所有对象的end_date最后一位,而非最后一个对象的完整end_date。 - 键名
end_date未加引号,Python会将其视为变量而非字符串键,运行时会报错。 - 变量名拼写错误:
reponse_monitor应为response_monitor。 - 判断
'detail' not in response_monitor逻辑有误,若response_monitor是数组,该判断永远为True(数组本身不直接包含'detail'字符串,需判断数组元素或接口返回格式)。
正确代码示例
直接获取数组的最后一个对象,再提取其end_date即可:
tk = token['token_type'] + " " + token['access_token'] url_enterprise = "url" response_monitor = requests.get(url_enterprise, headers={'Authorization': tk}).json() # 先验证返回格式合法且不为空 if isinstance(response_monitor, list) and len(response_monitor) > 0 and 'detail' not in response_monitor: # 取最后一个JSON对象的end_date last_end_date = response_monitor[-1]['end_date'] print(last_end_date)
关键说明
response_monitor[-1]:直接获取数组的最后一个元素(即目标JSON对象)。['end_date']:通过字符串键访问对象的end_date属性,注意键名必须加引号。- 增加类型和非空判断,避免接口返回非数组或空数组时触发报错。
内容的提问来源于stack exchange,提问作者wuad
相关产品推荐
相关产品推荐

