Perl HTTP Tiny响应

时间:2018-09-21 08:31:18

标签: json perl http

如何将HTTP::Tiny的JSON响应放入Perl?

use HTTP::Tiny;

my $response = HTTP::Tiny->new->get('http://example.com/');

die "Failed!\n" unless $response->{success};

print "$response->{status} $response->{reason}\n";

while (my ($k, $v) = each %{$response->{headers}}) {
   for (ref $v eq 'ARRAY' ? @$v : $v) {
        print "$k: $_\n";
   }
}

print $response->{content} if length $response->{content};

如何将$response->{content}放入变量以传递到html(tt2)?

1 个答案:

答案 0 :(得分:2)

您将像这样将您的内容传递给TT处理器:

use Template;

my $tt = Template->new;

$tt->process('some_template.tt', { content => $response->{content} })
  or die $tt->error;

也许您想先将其存储在中间标量中:

my $content = $response->{content};

$tt->process('some_template.tt', { content => $content })
  or die $tt->error;

也许您想在将TT的变量哈希传递给处理器之前先进行构建。

my %vars;

$vars{content} = $response->{content};

$tt->process('some_template.tt', \%vars)
  or die $tt->error;

或者您可以使用哈希引用代替实际的哈希:

my $vars;

$vars->{content} = $response->{content};

$tt->process('some_template.tt', $vars)
  or die $tt->error;

更新:在评论中,simbabque建议您实际上是在询问如何将JSON内容解码为数组或哈希。我同意这是解释您问题的另一种方式。

您需要使用JSON模块。看起来像这样:

use JSON;

my $json_parser = JSON->new; # Perhaps other options here, see docs.

my $decoded_json = $json_parser->decode($response->{content});