我需要解析json响应,但是我遇到了这段代码的问题,请帮我解决这个问题。
代码:
use strict;
use LWP::UserAgent;
use JSON qw( decode_json );
use Data::Dumper;
my $ua=LWP::UserAgent->new;
$ua->agent("firefox");
my $url="http://t-smos.com:8082/brand";
my $cont=&getContent($url);
my $decoded_json = decode_json( $cont );
#print Dumper $decoded_json;
print "Name: ", $decoded_json->{"name"},"\n";
sub getContent(){
my $url1=shift;
my $req=HTTP::Request->new("GET"=>$url1);
$req->header("X-Service-Token" => "506ecf24abe467aa269a5d12");
my $res=$ua->request($req);
my $content=$res->content;
return $content;
}
我收到错误..
Not a HASH reference in line 12. (print "Name: ", $decoded_json->{"name"},"\n";)
这是引用的问题吗?
答案 0 :(得分:2)
请改为尝试:
use strict;
use LWP::UserAgent;
use JSON qw( decode_json );
use Data::Dumper;
my $ua = LWP::UserAgent->new;
$ua->agent("firefox");
my $url = "http://t-smos.com:8082/brand";
my $response = $ua->get($url);
my $decoded_json = decode_json( $response->decoded_content );
print Dumper $decoded_json;
如果您在解析Perl HASH时遇到麻烦,则应提供Dumper
的示例输出。