如何递归遍历嵌套 JSON 目录树并准确获取文件的完整路径

冬丽同学_3762

冬丽同学_3762

2026-06-06

241人浏览

原创

如何递归遍历嵌套 JSON 目录树并准确获取文件的完整路径

本文讲解如何正确实现递归遍历多层嵌套的 json 目录结构(含 container、directory、file),精准定位目标文件并返回其从根容器开始的完整路径,避免因起始节点错误导致路径截断。

本文讲解如何正确实现递归遍历多层嵌套的 json 目录结构(含 container、directory、file),精准定位目标文件并返回其从根容器开始的完整路径,避免因起始节点错误导致路径截断。

在处理类似文件系统结构的嵌套 JSON 数据时(如 {'type': 'directory', 'name': 'xxx', 'children': [...]}),一个常见误区是:递归搜索时错误地跳过了顶层容器节点,直接从 children 数组开始遍历——这会导致路径丢失容器名和第一级目录名。

以问题中的 jsonData['testcontainer'] 为例:该键对应的值是一个列表,如

[{
  'type': 'directory',
  'name': 'testdir',
  'children': [...]
}]

注意:它不是一个字典,而是一个单元素列表,且该元素才是真正的根目录节点。若错误地写成 jsonData['testcontainer'][0]['children'](即跳过 'testdir' 节点),递归将从 testdir 的子项开始,自然无法生成 testcontainer/testdir/... 这样的完整路径。

✅ 正确做法是:始终从容器键对应的数据整体出发,先处理容器内所有顶层项(可能是 file 或 directory),再逐层深入 children。

arcgis-js
arcgis-js

提供 ArcGIS Maps SDK for JavaScript 开发辅助,涵盖 2D/3D 地图视图、图层管理、数据可视化、空间分析等功能模块的参考和示例指导。

下载

以下是修复后的完整可运行教程代码:

def find_file_path(data, filename, container='', current_path=''):
    """
    递归查找指定文件名的完整路径

    Args:
        data: 当前待搜索的数据(list of items)
        filename: 目标文件名(str)
        container: 当前所属容器名(str,用于构造路径前缀)
        current_path: 当前累积路径(不含容器名,如 '/testdir/test3')

    Returns:
        dict with keys 'container', 'filename', 'path' (full path including container), or None
    """
    for item in data:
        # 检查当前项是否为匹配的文件
        if item.get('type') == 'file' and item.get('name') == filename:
            full_path = f"/{container}{current_path}/{filename}".replace('//', '/')
            return {
                'container': container,
                'filename': filename,
                'path': full_path
            }

        # 若为目录,递归搜索其 children,并更新路径
        elif item.get('type') == 'directory':
            # 进入该目录:路径追加目录名
            new_path = f"{current_path}/{item['name']}"
            result = find_file_path(
                item.get('children', []), 
                filename, 
                container, 
                new_path
            )
            if result:
                return result

    return None

# 主搜索函数:遍历所有容器
def search_all_containers(json_data, filename):
    """在全部容器中搜索文件,返回首个匹配结果"""
    for container_name, container_items in json_data.items():
        result = find_file_path(
            container_items, 
            filename, 
            container=container_name, 
            current_path=''
        )
        if result:
            return result
    return None

# 示例使用
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'}]}]
}

# 查找 test3.txt
result = search_all_containers(jsonData, 'test3.txt')
if result:
    print("✅ 找到文件:", result['path'])  # 输出: /testcontainer/testdir/test3.txt
else:
    print("❌ 文件未找到")

? 关键注意事项:

  • ✅ 容器数据是 list,不是 dict:jsonData['testcontainer'] 是一个列表,必须整体传入递归函数,而非取 [0]['children'];
  • ✅ 路径拼接需统一规范:使用 / 分隔,通过 replace('//', '/') 防止重复斜杠;
  • ✅ 支持全容器扫描:search_all_containers() 可自动遍历所有 top-level 容器键,无需手动指定;
  • ⚠️ 健壮性增强:添加 .get() 避免 KeyError,对缺失 type 或 name 字段更安全;
  • ? 调试建议:临时在递归函数中加入 print(f"Searching {current_path} in {container}") 可直观跟踪遍历过程。

通过此方案,test3.txt 将被准确定位为 testcontainer/testdir/test3.txt,完全符合预期路径结构。

相关文章

PHP速学视频免费教程(入门到精通)
PHP速学视频免费教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

相关标签:

json python js

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
python打包成可执行文件
python打包成可执行文件

本专题为大家带来python打包成可执行文件相关的文章,大家可以免费的下载体验。

2023.07.20

1851

4

python能做什么
python能做什么

python能做的有:可用于开发基于控制台的应用程序、多媒体部分开发、用于开发基于Web的应用程序、使用python处理数据、系统编程等等。本专题为大家提供python相关的各种文章、以及下载和课程。

2023.07.25

4984

7

format在python中的用法
format在python中的用法

Python中的format是一种字符串格式化方法,用于将变量或值插入到字符串中的占位符位置。通过format方法,我们可以动态地构建字符串,使其包含不同值。php中文网给大家带来了相关的教程以及文章,欢迎大家前来阅读学习。

2023.07.31

1789

3

python教程
python教程

Python已成为一门网红语言,即使是在非编程开发者当中,也掀起了一股学习的热潮。本专题为大家带来python教程的相关文章,大家可以免费体验学习。

2023.08.03

29957

23

python环境变量的配置
python环境变量的配置

Python是一种流行的编程语言,被广泛用于软件开发、数据分析和科学计算等领域。在安装Python之后,我们需要配置环境变量,以便在任何位置都能够访问Python的可执行文件。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

2023.08.04

3567

5

python eval
python eval

eval函数是Python中一个非常强大的函数,它可以将字符串作为Python代码进行执行,实现动态编程的效果。然而,由于其潜在的安全风险和性能问题,需要谨慎使用。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

2023.08.04

3587

5

scratch和python区别
scratch和python区别

scratch和python的区别:1、scratch是一种专为初学者设计的图形化编程语言,python是一种文本编程语言;2、scratch使用的是基于积木的编程语法,python采用更加传统的文本编程语法等等。本专题为大家提供scratch和python相关的文章、下载、课程内容,供大家免费下载体验。

2023.08.11

1223

5

python合并两个列表
python合并两个列表

Python是一种强大的编程语言,具有许多方便的功能和工具。在Python中,有多种方法可以合并两个列表。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

2023.08.10

616

4

python是前端还是后端
python是前端还是后端

Python属于前端也属于后端,其灵活性和丰富的生态系统使得开发人员能够在不同的领域中灵活运用。本专题为大家提供python相关的文章、下载、课程内容,供大家免费下载体验。

2023.08.11

2783

5

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程