我有一个嵌套的哈希表,如下所示:
{"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"
}
]
真的很迷茫。你能弄清楚这里有什么问题吗?