在perl中访问json结构的值 [英] Accessing values of json structure in perl

查看:143
本文介绍了在perl中访问json结构的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  person => 

我有一个json结构,我正在解码,看起来像这样: {
city => Chicago,
id => 123,
name => Joe Smith,
pets => {
cats => [
{age => 6,name => cat1,type => 连体,体重=> 10千克},
{age => 10,name => cat2,type => 连体,体重=> 13公斤},
],
狗=> [
{age => 7,name => dog1,type => 连体,体重=> 20公斤},
{age => 5,name => dog2,type => 连体,体重=> 15公斤},
],
},
},
}

我可以打印 city id name 做:

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

然而,我不确定如何打印 pets->猫 pets->狗。可以通过以下方式将它们转储:

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

但我不确定如何通过假设你的 $ listing 是一个

>人,你必须解引用数组和哈希引用。

 #只要我们假设$ listing是一个person 
#这是在您发布在
#问题中的foreach内部。

#这将打印所有猫的名字
foreach my $ cat(@ {$ {cat}})
{
#here $ cat是散列引用

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

等其他内容。



要符合从结构中可以做到这一点:

  say $ listing-> {pets}  - > {cats}  - > ; [0]  - > {名称}; #这将打印'cat1'


I have a json structure that I'm decoding that looks like this:

  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" },
              ],
    },
  },
}

I'm able to print the city, id, name by doing:

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

however, I'm unsure of how to print the pets->cats or pets->dogs. I'm able to do a dump of them by:

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

but I'm not sure how to access them through the hash structure.

解决方案

Assuming your $listing is a person you have to dereference array and hash refs.

# 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
}

and so on for other stuff.

To access them from the structure you can do:

say $listing->{pets}->{cats}->[0]->{name}; # this will print 'cat1'

这篇关于在perl中访问json结构的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆