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

Python读取复杂JSON提取键值遇列表无keys属性的问题解决

问题解决及实现代码

错误原因

运行代码时报错A list object does not have an attribute keys,是因为data是列表类型,而列表没有keys()方法。结合你给出的JSON结构,推测response是包含目标字典的列表(比如response = [你的JSON字典]),所以json.loads后得到的是列表,需要先取出里面的字典对象。

修正后的代码

import json

# 处理response,确保拿到字典对象
if isinstance(response, list):
    data = response[0]
else:
    data = response

# 筛选数字键对应的task并整理格式
table_data = []
for key, content in data.items():
    # 只处理键为数字且包含task字段的条目
    if key.isdigit() and "task" in content:
        task_str = ", ".join(content["task"])
        table_data.append({"id": key, "task": task_str})

# 输出Markdown表格
print("| id | task |")
print("|----|------|")
for item in table_data:
    print(f"| {item['id']} | {item['task']} |")

最终输出表格

idtask
1wakeup, getready
2brush, shower
3brush, shower

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 07:21:35