在perl中访问json结构的值
发布时间:2020-12-15 21:16:50 所属栏目:大数据 来源:网络整理
导读:我有一个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 = [ {
我有一个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; 但我不确定如何通过哈希结构访问它们. 解决方法
假设您的$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' (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |