在perl中访问json结构的值

前端之家收集整理的这篇文章主要介绍了在perl中访问json结构的值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个json结构,我正在解码,看起来像这样:
person => {
    city => "Chicago",id => 123,name => "Joe Smith",pets => {
      cats => [
                { age => 6,name => "cat1",type => "siamese",weight => "10 kilos" },{ age => 10,name => "cat2",weight => "13 kilos" },],dogs => [
                { age => 7,name => "dog1",weight => "20 kilos" },{ age => 5,name => "dog2",weight => "15 kilos" },},}

我可以通过以下方式打印城市,id,名称

foreach my $listing ($decoded->{person})
{ 
    my $city = $listing->{city};
    my $name = $listing->{name};
    name - $city - \n";
}

但是,我不确定如何打印宠物 – >猫或宠物 – >狗.我可以通过以下方式转储它们:

my @pets = $listing->{pets}->{cats};
dump @pets;

但我不确定如何通过哈希结构访问它们.

解决方法

@H_404_17@ 假设您的$listing是一个人,您必须取消引用数组和散列引用.
# as long as we are assuming $listing is a person
# this goes inside the foreach you posted in your
# question.

# this will print all cats' names
foreach my $cat ( @{ $listing->{pets}->{cats} } )
{
    # here $cat is a hash reference

    say $cat->{name}; # cat's name
}

等等其他东西.

要从结构中访问它们,您可以执行以下操作:

say $listing->{pets}->{cats}->[0]->{name}; # this will print 'cat1'
原文链接:https://www.f2er.com/Perl/172908.html

猜你在找的Perl相关文章