Search code examples
perllwp

how to get output of LWP requests in json format in perl


I am not getting of how to parse the output of LWP post request in json format. I am using below code:-

use LWP::UserAgent;
use JSON;

my $ua = LWP::UserAgent->new;
my $server_endpoint = URL;                   #URL contains actual URL

# set custom HTTP request header fields
my $req = HTTP::Request->new( POST => $server_endpoint );
$req->header( 'content-type' => 'application/json' );
$req->header( 'Accept'       => 'application/json' );

# add POST data to HTTP request body
my $post_data = '{ "auth": {"tenantName":"****", "passwordCredentials": {"username":"****","password":"****"} }}';
$req->content($post_data);

my $resp = $ua->request($req);
if ( $resp->is_success ) {
    my $message = $resp->decoded_content;
    print "Received reply: $message\n\n\n";
    $tojson   = to_json($resp);
    $fromjson = from_json($tojson);
    print "Token id is " . $fromjson->{'access'}{'token'}{'tenant'}{'id'} . "\n";
}

I want to fetch token id by using hashes. But I am not getting any output. So is there any way to convert the output in json format so that we can easily get the token id ?


Solution

  • $tojson   = to_json($resp);
    $fromjson = from_json($tojson);
    

    shouldn't it be $fromjson = from_json($message); ?