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

Python解析API返回JSON列表获取'data'值报错求助

问题解析与解决方法

错误根源

你犯了两个关键错误:

  1. 使用json.dumps(response)把Python对象转换成了JSON格式字符串,字符串无法通过['data']这种键名索引取值;
  2. 原始API响应本身是一个列表(外层带[]),而非单个字典,即使直接处理响应对象,也不能直接用键名访问。

正确处理步骤

情况1:直接使用API返回的Python对象

API返回的response已经是Python列表类型,无需转成字符串,直接按以下方式提取:

# 取列表第一个元素(字典),再提取data字段
target_data = response[0]['data']
print(target_data)  # 输出:testing.test.com

情况2:若响应是JSON字符串(需解析)

如果你的response是原始JSON字符串,要用json.loads()反序列化为Python对象,再取值:

import json
# 假设response是原始JSON字符串
response_str = '[{"_id": "~1742209152", "id": "~1742209152", "createdBy": "test@test.com", "createdAt": 1666089754558, "_type": "case_artifact", "dataType": "domain", "data": "testing.test.com", "startDate": 1666089754558, "tlp": 2, "pap": 2, "tags": ["Domain"], "ioc": True, "sighted": True, "message": "", "reports": {}, "stats": {}, "ignoreSimilarity": False}]'
response = json.loads(response_str)
target_data = response[0]['data']
print(target_data)

关键知识点

  • json.dumps():将Python对象转为JSON字符串(用于输出或存储)
  • json.loads():将JSON字符串转为Python对象(用于解析输入)
  • 列表只能通过整数索引(如[0])访问元素,字典才能通过键名(如['data'])取值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 21:40:50