JSON目录结构遍历异常:无法获取文件完整路径求助
问题分析
你的代码存在两个核心问题,导致路径错误且无法遍历所有容器:
- 调用时跳过关键目录:你直接传入
jsonData['testcontainer'][0]['children'],相当于从testdir的子元素开始遍历,完全漏掉了testdir本身,最终路径自然缺失这个目录。 - 函数未支持遍历所有容器:原函数只能处理单个容器内的结构,无法自动遍历jsonData里的所有顶层容器。
修复后的代码
jsonData = { '01042014': [{'type': 'directory', 'name': 'Apr1', 'children': [{'type': 'directory', 'name': 'Apr2', 'children': [{'type': 'directory', 'name': 'Apr3', 'children': [{'type': 'file', 'name': 'inapr3.txt'}, {'type': 'file', 'name': 'test1.txt'}]}, {'type': 'file', 'name': 'inapr2.txt'}]}, {'type': 'file', 'name': 'inapr1.txt'}, {'type': 'file', 'name': 'test2.txt'}]}, {'type': 'file', 'name': 'inroot.txt'}, {'type': 'file', 'name': 'test1.txt'}], 'container0': [{'type': 'directory', 'name': 'dir0', 'children': [{'type': 'file', 'name': 'test0.txt'}]}], 'container1': [{'type': 'directory', 'name': 'dir1', 'children': [{'type': 'file', 'name': 'test1.txt'}]}], 'container2': [{'type': 'directory', 'name': 'dir2', 'children': [{'type': 'file', 'name': 'test2.txt'}]}], 'test1': [{'type': 'directory', 'name': 'testdir0', 'children': [{'type': 'file', 'name': 'test1.txt'}]}], 'test2': [{'type': 'directory', 'name': 'testdir', 'children': []}], 'testcontainer': [{'type': 'directory', 'name': 'testdir', 'children': [{'type': 'directory', 'name': 'Test10', 'children': []}, {'type': 'directory', 'name': 'testdir2', 'children': [{'type': 'directory', 'name': 'test3', 'children': [{'type': 'file', 'name': 'test3file.txt'}]}, {'type': 'file', 'name': 'test2file.txt'}]}, {'type': 'file', 'name': '2ndcopy.txt'}, {'type': 'file', 'name': 'test0.txt'}, {'type': 'file', 'name': 'test1.txt'}, {'type': 'file', 'name': 'test2.txt'}, {'type': 'file', 'name': 'test3.txt'}]}] } def find_file_path(data, filename): # 遍历所有顶层容器 for container_name, items in data.items(): # 递归处理当前容器内的元素 def traverse(items, current_path): for item in items: if item['type'] == 'file' and item['name'] == filename: return f"{container_name}{current_path}/{item['name']}" elif item['type'] == 'directory': # 支持查找目录本身(如果需要) if item['name'] == filename: return f"{container_name}{current_path}/{item['name']}" # 递归遍历子目录 result = traverse(item.get('children', []), f"{current_path}/{item['name']}") if result: return result return None result = traverse(items, "") if result: return result return None # 示例调用 filename = 'test3.txt' full_path = find_file_path(jsonData, filename) if full_path: print(full_path) # 输出:testcontainer/testdir/test3.txt else: print("File not found.")
修复说明
- 新增顶层容器遍历:函数自动遍历jsonData里的所有顶层容器(如
testcontainer、container0等),无需手动指定单个容器。 - 修正路径起点:不再跳过容器内的根目录(如
testdir),递归时从容器名称开始逐步拼接完整路径。 - 简化逻辑:把递归逻辑封装成内部函数,减少冗余参数传递,代码结构更清晰。
内容的提问来源于stack exchange,提问作者SINCHANA
相关产品推荐
相关产品推荐

