我为脚本提供了JSON数据文件。然后,我已使用decode_json解码了JSON数据...
open my $fh, '<:encoding(UTF-8)', $file ir die;
my $jsondata = do {local $/; <$fh> };
my $data = decode_json($jsondata);
#print Dumper $data
#I am trying to write a foreach loop in here to pull particular bits of
#the information out that I want to display (as detailed further below)
close $fh;
Dumper输出看起来像这样...
$VAR1 = [
{
'DataName' => 'FileOfPetsAcrossTheWorld',
'Information001' => [
{
'Name' => Steve,
'Sex' => 'Male',
'Age' => 24,
'Animals' => [
'Dog',
'Cat',
'Hamster',
'Parrot
],
'Location' => 'London',
},
{
'Name' => Dave,
'Sex' => 'Male',
'Age' => 59,
'Animals' => [
'Fish',
'Horse',
'Budgie',
],
'Location' => 'Paris',
},
{
'Name' => Sandra,
'Sex' => 'Female',
'Age' => 44,
'Animals' => [
'Snake',
'Crocodile',
'Flamingo',
],
'Location' => 'Syndey',
}
]
}
];
我正在尝试使用foreach外观从此数据结构检索输出,以便我可以打印输出...
Dataname: FileOfPetsAcrossTheWorld
Name: Steve
Animals: Dog, Cat, Parrot, Hamster
Location: London
Name: Dave
Animals: Fish, Horse, Budgie
Location: Paris
Name: Sandra
Animals: Snake, Crocodile, Flamingo
Location: Sydey
我尝试了各种不同的foreach循环和来自在线资源的哈希引用代码片段(以及一些我曾经使用过并曾工作过的代码片段)来迭代并从哈希中提取数据等,但是我似乎无法使其在此工作案件。在其他错误中,我收到诸如“在...处没有哈希引用”之类的错误。
将这种信息从这种数据结构中提取出来的正确方法是什么?
答案 0 :(得分:1)
for my $hash (@$data) {
say "Dataname: $hash->{DataName}";
for my $info (@{ $hash->{Information001} }) {
say "Name: $info->{Name}";
say 'Animals: ', join ', ', @{ $info->{Animals} };
say "Location: $info->{Location}";
say "";
}
}
动物的顺序对于史蒂夫而言是不同的。悉尼被拼成“ Sydey”。