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']} |")
最终输出表格
| id | task |
|---|---|
| 1 | wakeup, getready |
| 2 | brush, shower |
| 3 | brush, shower |
内容的提问来源于stack exchange,提问作者RData
相关产品推荐
相关产品推荐

