1

我有一个嵌套的哈希表,如下所示:

{"a": {"b": {"c": {"d": "", "e": ""},
             "m": ""},
       "f": ""},
 "h": {"i": {"j": "", "k": ""}
      }
}

我想把它转换成这样的格式:

[
    {"title": "a", "isFolder": true,
        "children": [
            {"title": "b", "isFolder": true",
                "children": [
                    {"title": "c", "isFolder": true",
                        "children": [
                            {"title": "d"},
                            {"title": "e"}
                        ]
                    },
                    {"title": "m"}
                ]
            },
            {"title": "f"},
            {"title": "g"}
        ]
    },
    {"title": "h", "isFolder": "true",
        "children": [
            {"title": "i", "isFolder": "true",
                "children": [
                    {"title": "j"},
                    {"title": "k"}
                ]
            }
        ]
    }
]

于是我写了一个程序:

#!/usr/bin/perl

use JSON;

$json = JSON->new->allow_nonref;

$struct = [];
sub convertRaw() {
    ($raw, $ts) = @_;

    foreach (keys %$raw) {
        if ($raw->{$_}) {
            push @$ts, {"title" => $_, "isFolder" => "true", "children" => []};
            &convertRaw($raw->{$_}, @$ts[-1]->{"children"});
        }
        else {
            push @$ts, {"title" => $_};
        }
    }
}

$raw_struct = {"a"=> {"b"=> {"c"=> {"d"=> "", "e"=> ""},
                             "m"=> ""},
                      "f"=> ""},
               "h"=> {"i"=> {"j"=> "", "k"=> ""}
                     }
              };

&convertRaw($raw_struct, $struct);

print $json->pretty->encode($struct)."\n";

但是,输出结果是这样的:

[
   {
      "isFolder" : "true",
      "children" : [
         {
            "isFolder" : "true",
            "children" : [
               {
                  "title" : "k"
               },
               {
                  "title" : "j"
               },
               {
                  "title" : "a"
               }
            ],
            "title" : "i"
         }
      ],
      "title" : "h"
   }
]

真的很迷茫。你能弄清楚这里有什么问题吗?

4

1 回答 1

1

您有全局声明的变量$raw$ts. 所以子元素处理期间的哈希更新会影响父元素的未来处理。将它们声明为词法范围的变量

sub convertRaw {
    my ($raw, $ts) = @_;
    # the rest of the code
于 2013-03-27T06:11:40.537 回答