如何正确遍历嵌套 JSON 目录结构并获取文件的完整路径

小磊同学_4105

小磊同学_4105

2026-06-06

677人浏览

原创

本文详解如何递归遍历多层嵌套的 json 树形结构(含容器、目录、文件),精准定位目标文件并生成包含容器名与完整层级路径的绝对路径,避免因起始节点错误导致路径截断。

本文详解如何递归遍历多层嵌套的 json 树形结构(含容器、目录、文件),精准定位目标文件并生成包含容器名与完整层级路径的绝对路径,避免因起始节点错误导致路径截断。

在处理类似文件系统结构的嵌套 JSON 数据时,一个常见误区是:将递归起点设为 children 数组而非容器根节点,从而丢失父目录名(如 'testdir'),导致路径不完整(如输出 testcontainer/test3.txt 而非 testcontainer/testdir/test3.txt)。

问题代码中关键错误在于:

container_data = jsonData['testcontainer'][0]['children']  # ❌ 错误:跳过了 'testdir' 这一层

这使得递归从 'testdir' 的子节点(即 children)开始,自然无法将 'testdir' 纳入路径。

✅ 正确做法是:从容器顶层条目(即 jsonData['testcontainer'])开始遍历,让递归函数自行处理 type='directory' 节点的命名与路径拼接。

Expanso yaml-to-json
Expanso yaml-to-json

使用 Expanso Edge 管道将 YAML 输入转换为 JSON 格式。

下载

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

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, container='', current_path=''):
    """
    递归查找文件并构建完整路径

    Args:
        data: 当前待遍历的数据(list of dict)
        filename: 目标文件名(str)
        container: 当前所属容器名(str)
        current_path: 当前累积路径(不含容器前缀,如 '/testdir/testdir2')

    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}"
            return {
                'container': container,
                'filename': filename,
                'path': full_path[1:]  # 去掉开头的 '/'
            }

        # 处理目录节点:先加入当前目录名,再递归 children
        elif item.get('type') == 'directory':
            # 构建进入该目录后的新路径
            new_path = f"{current_path}/{item['name']}"
            # 递归搜索其 children
            result = find_file_path(
                item.get('children', []), 
                filename, 
                container, 
                new_path
            )
            if result:
                return result

    return None

# ✅ 正确调用方式:传入整个容器列表(如 jsonData['testcontainer'])
target_container = 'testcontainer'
filename = 'test3.txt'

# 注意:jsonData['testcontainer'] 是一个 list,可能含多个根目录项
container_entries = jsonData.get(target_container, [])
result = find_file_path(container_entries, filename, container=target_container)

if result:
    print(result['path'])  # 输出:testcontainer/testdir/test3.txt
else:
    print(f"File '{filename}' not found in container '{target_container}'.")

? 关键要点总结:

  • 路径构建时机:目录名应在进入该目录时(即 new_path = f"{current_path}/{item['name']}")加入路径,而非在匹配到文件时临时拼接;
  • 容器传递一致性:container 参数需在每次递归中保持不变,确保最终路径包含正确的容器前缀;
  • 健壮性增强:使用 .get() 防止 KeyError;支持容器内存在多个同名根目录项;
  • 全局搜索扩展:若需跨所有容器搜索,只需外层遍历 jsonData.items() 并对每个 container_name, entries 调用 find_file_path。

通过以上修正,即可准确生成如 testcontainer/testdir/test3.txt 这类符合真实目录层级的完整路径,真正实现树形结构的深度优先精确定位。

相关文章

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

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

下载

相关标签:

json js

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

相关专题

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

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

2023.07.20

1891

4

python能做什么
python能做什么

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

2023.07.25

5184

7

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

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

2023.07.31

1829

3

python教程
python教程

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

2023.08.03

31357

23

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

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

2023.08.04

3707

5

python eval
python eval

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

2023.08.04

3727

5

scratch和python区别
scratch和python区别

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

2023.08.11

1243

5

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

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

2023.08.10

616

4

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

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

2023.08.11

2883

5

热门下载

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

精品课程

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