0

我需要解析 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";)

这是引用的问题吗?

4

1 回答 1

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;

笔记

Dumper如果您在解析 Perl HASH 时遇到问题,您应该提供一个示例输出。

于 2013-02-19T14:52:12.363 回答