讲师中心 微信公众号
AI工具推荐 视频效率加速

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

小磊同学_4105

小磊同学_4105

发布时间:2026-06-06 14:00:37

|

677人浏览过

|

来源于php中文网

原创

本文详解如何递归遍历多层嵌套的 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 这类符合真实目录层级的完整路径,真正实现树形结构的深度优先精确定位。

热门AI工具

更多
超级简历WonderCV

一款AI办公效率工具,主要用于免费求职简历模版下载制作,应届生职场人必备简历制作神器,适合需要提升相关任务效率的用户。

DeepSeek

DeepSeek是一款面向对话、写作、编程和推理场景的AI大模型工具。

豆包大模型

豆包大模型是一款由字节跳动推出的企业级大语言模型服务平台。

Lovart
Lovart Hot

一款面向视觉设计创作的AI设计平台,可通过智能体和画布工作流辅助制作海报、Logo、网页、PPT及其他视觉内容。

WorkBuddy

一款AI办公效率工具,主要用于腾讯云推出的AI原生桌面智能体工作台,适合需要提升相关任务效率的用户。

讯飞智作

讯飞智作是一款AI视频创作工具,AI文本配音工具,数字人课程、营销视频制作。

小橡皮AI

一款AI工具,主要用于小橡皮一键去AI味,将机器味重的内容改得更有活人感,防止因为 AI 内容被平台打上 AI 标签,以及限流,适合需要提升相关任务效率的用户。

UP简历
UP简历 Hot

一款AI办公效率工具,主要用于基于AI技术的免费在线简历制作工具,适合需要提升相关任务效率的用户。

Atoms
Atoms Hot

Atoms是一款AI智能体工具,第一支自动构建真实业务的 AI 团队。

相关专题

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

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

1891

2023.07.20

python能做什么
python能做什么

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

5184

2023.07.25

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

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

1829

2023.07.31

python教程
python教程

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

31377

2023.08.03

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

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

3707

2023.08.04

python eval
python eval

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

3727

2023.08.04

scratch和python区别
scratch和python区别

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

1243

2023.08.11

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

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

616

2023.08.10

Postman身份认证怎么配置
Postman身份认证怎么配置

本专题从实际API接口调试场景出发,讲解Postman身份认证的完整配置流程,包括常见认证协议介绍、授权参数设置、访问令牌填写、OAuth 2.0授权及认证失败排查,帮助用户正确完成接口授权与访问验证。

0

2026.11.06

热门下载

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

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn