123, name => "Joe Smith",-6ren">
gpt4 book ai didi

json - 在 perl 中访问 json 结构的值

转载 作者:行者123 更新时间:2023-12-02 11:25:31 24 4
gpt4 key购买 nike

我有一个正在解码的 json 结构,如下所示:

  person => {
city => "Chicago",
id => 123,
name => "Joe Smith",
pets => {
cats => [
{ age => 6, name => "cat1", type => "siamese", weight => "10 kilos" },
{ age => 10, name => "cat2", type => "siamese", weight => "13 kilos" },
],
dogs => [
{ age => 7, name => "dog1", type => "siamese", weight => "20 kilos" },
{ age => 5, name => "dog2", type => "siamese", weight => "15 kilos" },
],
},
},
}

我可以打印 city , id , name通过做:
foreach my $listing ($decoded->{person})
{
my $city = $listing->{city};
my $name = $listing->{name};
name - $city - \n";
}

但是,我不确定如何打印 pets->catspets->dogs .我可以通过以下方式转储它们:
my @pets = $listing->{pets}->{cats};
dump @pets;

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

最佳答案

假设您的 $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'

关于json - 在 perl 中访问 json 结构的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8258387/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com