Python JSON关联值查找:Taskwarrior依赖层级展示实现求助
嘿,别担心编程新手的身份——大家都是从复制代码、摸爬滚打开始的!你的思路完全正确,我们一步步来实现Taskwarrior任务的层级依赖展示,过程其实很直观:
实现Taskwarrior依赖层级展示的分步指南
1. 先把Taskwarrior任务导出为JSON
首先用Taskwarrior的命令行工具把所有任务导出成JSON格式,这样Python才能轻松处理:
task export --json > tasks.json
执行这个命令后,你会得到一个tasks.json文件,里面存着所有任务的结构化数据。
2. 用Python加载JSON数据
接下来写几行Python代码读取这个文件,把JSON转成Python能操作的字典列表:
import json # 读取并解析JSON文件 with open('tasks.json', 'r') as f: tasks = json.load(f)
现在tasks变量就是一个列表,每个元素都是一个任务字典,包含UUID、描述、depends这些字段。
3. 建立UUID到任务的快速映射
为了不用每次找子任务都遍历整个列表,我们先做一个“UUID-任务”的字典,这样查找子任务会快很多:
# 生成UUID到任务的映射字典 task_map = {task['uuid']: task for task in tasks}
之后只要知道子任务的UUID,直接用task_map[目标UUID]就能拿到对应的任务数据。
4. 匹配父任务和子任务
现在遍历所有任务,找出带有depends字段的父任务,再根据depends里的UUID找到对应的子任务:
# 用来存储最终层级结构的列表 task_hierarchy = [] for task in tasks: # 检查当前任务是否是父任务(有depends字段) if 'depends' in task: # depends的值是逗号分隔的UUID字符串,先拆分并清理空格 child_uuid_list = [uuid.strip() for uuid in task['depends'].split(',')] # 根据UUID找到对应的子任务(过滤掉不存在的UUID) child_tasks = [task_map[uuid] for uuid in child_uuid_list if uuid in task_map] # 把父任务和子任务组成一组,加入层级列表 task_hierarchy.append({ 'parent': task, 'children': child_tasks })
这里要注意depends的格式是逗号分隔的UUID,所以要拆分并去掉可能的空格,同时过滤掉不存在的UUID(避免报错)。
5. 可视化层级结构
最后我们可以写一个简单的函数,把层级结构用缩进的方式打印出来,看起来更清晰:
def print_task_hierarchy(hierarchy, indent_level=0): for item in hierarchy: # 打印父任务信息 indent = " " * indent_level print(f"{indent}父任务: {item['parent']['description']} (UUID: {item['parent']['uuid']})") print(f"{indent}子任务:") # 打印子任务 for child in item['children']: print(f"{indent} - {child['description']} (UUID: {child['uuid']})") # 递归处理子任务的依赖(如果子任务也是父任务) child_hierarchy = [] for child in item['children']: if 'depends' in child: grandchild_uuid_list = [uuid.strip() for uuid in child['depends'].split(',')] grandchild_tasks = [task_map[uuid] for uuid in grandchild_uuid_list if uuid in task_map] child_hierarchy.append({'parent': child, 'children': grandchild_tasks}) if child_hierarchy: print_task_hierarchy(child_hierarchy, indent_level + 1) # 调用函数打印层级 print_task_hierarchy(task_hierarchy)
这个函数会递归打印所有嵌套的依赖关系,不管你的任务层级有多深都能展示出来。
小提示
- 如果你的任务里有循环依赖(比如A依赖B,B又依赖A),可以加个已打印UUID的集合来避免无限递归。
- 你也可以修改输出格式,比如生成Markdown列表或者把结果保存成新的JSON文件,完全看你的需求。
内容的提问来源于stack exchange,提问作者Atilla
相关产品推荐
相关产品推荐

