如何使用Perl从服务器解析JSON / REST数据

时间:2016-09-18 15:35:47

标签: json perl rest

我试图使用Perl解析服务器的JSON输出。 REST数据的连接和下载是可以的,我只需要帮助解析返回的数据。以下是我的代码片段:

my $response = HTTP::Tiny->new->get($SERVER_ADDR);
if ($response->{success})
{
    my $html = $response->{content};
    @LINES = split /\n/, $html;
    chomp(@LINES);
    print("Lines: '@LINES'\n"); # ZZZ
    my $decoded_json = decode_json( $html );
    print Dumper $decoded_json;
}
else
{
    print "Failed: $response->{status} $response->{reasons}";
}

以下是结果:

Lines: '{"players":[{"currentlyOnline":false,"timePlayed":160317,"name":"MarisaG","lastPlayed":1474208741470}]}'
$VAR1 = {
      'players' => [
                     {
                       'currentlyOnline' => bless( do{\(my $o = 0)}, 'JSON::PP::Boolean' ),
                       'timePlayed' => 160317,
                       'lastPlayed' => '1474208741470',
                       'name' => 'MarisaG'
                     }
                   ]
    };

"玩家"下会有多个参赛作品。对于现在登录的每个玩家。有什么提示吗?

1 个答案:

答案 0 :(得分:2)

我不确定你在问什么。您已通过调用decode_json()成功解析了JSON。您现在在$decoded_json中有一个数据结构。您对Dumper()的调用显示了该数据的结构。它是一个带有单个键players的哈希引用。与该键关联的值是数组引用。引用数组中的每个元素都是另一个哈希值。

因此,例如,你可以用这样的代码打印所有玩家的名字。

foreach (@{ $decoded_json->{players} }) {
  say $_->{name};
}
相关问题