You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Perl生成符合Fancytree预期JSON格式的目录树

用Perl生成符合Fancytree预期格式的目录树JSON

我来帮你调整代码,让它生成Fancytree需要的JSON结构。你现有的代码能遍历目录并生成嵌套哈希,但Fancytree要求每个节点包含title(显示名称)和children(子节点数组)这类字段,咱们来修改实现:

原代码回顾

先看你写的目录遍历代码:

sub get_tree { 
    my ($gpath) = @_; 
    my %r; 
    use File::Find; 
    my $c = sub { 
        my $dir = $File::Find::dir; 
        my $r = \%r; 
        my $tdir = $dir; 
        $tdir =~ s|^\Q$gpath\E/?||; 
        $r = $r->{$_} ||= {} for split m|/|, $tdir; 
    }; 
    find($c, $gpath); 
    return \%r; 
}

这段代码生成的是键为目录名、值为子目录哈希的结构,编码后不符合Fancytree的节点格式要求。

修改后的完整实现

我们需要添加一个递归转换函数,把哈希结构转换成Fancytree预期的节点数组:

use strict;
use warnings;
use File::Find;
use JSON;

sub hash_to_fancytree {
    my ($hash) = @_;
    my @nodes;
    foreach my $name (sort keys %$hash) {
        my $node = { title => $name };
        # 如果有子目录,递归生成children数组
        if (%{ $hash->{$name} }) {
            $node->{children} = hash_to_fancytree($hash->{$name});
        }
        push @nodes, $node;
    }
    return \@nodes;
}

sub get_tree { 
    my ($gpath) = @_; 
    my %r; 
    my $c = sub { 
        my $dir = $File::Find::dir; 
        my $r = \%r; 
        my $tdir = $dir; 
        $tdir =~ s|^\Q$gpath\E/?||; 
        # 跳过空路径(即根目录本身)
        return unless $tdir;
        $r = $r->{$_} ||= {} for split m|/|, $tdir; 
    }; 
    find($c, $gpath); 
    # 把哈希结构转换成Fancytree节点格式
    return hash_to_fancytree(\%r);
}

# 示例用法
my $tree = get_tree('/path/to/your/directory');
print encode_json($tree);

代码说明

  1. hash_to_fancytree函数:递归遍历目录哈希,将每个目录名转为title字段;如果当前目录有子目录,就递归生成children数组,完全匹配Fancytree的节点结构。
  2. 修改get_tree:添加了对根目录的跳过逻辑(避免生成空标题节点),最后调用转换函数返回符合要求的节点数组。
  3. JSON编码:使用JSON模块的encode_json方法,输出标准的JSON格式。

预期输出示例

编码后的JSON会是这样的结构,完全符合Fancytree的要求:

[
  {
    "title": "dir1",
    "children": [
      {
        "title": "sub-dir1"
      },
      {
        "title": "sub-dir2"
      }
    ]
  },
  {
    "title": "dir3"
  }
]

内容的提问来源于stack exchange,提问作者Ilia Ross

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:22:32