Raja
Raja

Reputation: 3627

Perl LWP returns JSON output as string

I am using Perl LWP::UserAgent to get response from an API. Everything works good except one issue.

The API that i am using it returns response in JSON format. But I am getting it as string when i get the response through LWP module, Something like below.

$VAR1 = '
{"status":"success","data":[{"empid":"345232","customername":"Lee gates","dynamicid":"2342342332sd32423"},{"empid":"36.VLXP.013727..CBCL..","customername":"Lee subdirectories","dynamicid":"223f3423dsf23423423"}],"message":""}'

I did "print Dumper $response" to get the output.

One more thing, The challenge is that my client do not want to go with Perl module for JSON (use JSON::Parse 'parse_json';).

Upvotes: 1

Views: 802

Answers (2)

brian d foy
brian d foy

Reputation: 132802

Mojolicious handles this for you through when you call the json method on the response object:

use Mojo::UserAgent;

my $ua = Mojo::UserAgent->new;
my $tx = $ua->get( 'https://www.example.com/api/endpoint' );
my $data = $tx->res->json;

Upvotes: 0

stevieb
stevieb

Reputation: 9296

You need to decode the JSON string into a Perl data structure. If your version of perl is 5.14+, JSON::PP is included in core, so nothing to install.

use warnings;
use strict;

use Data::Dumper;
use JSON::PP qw(decode_json);

my $json = '{"status":"success","data":[{"empid":"345232","customername":"Lee gates","dynamicid":"2342342332sd32423"},{"empid":"36.VLXP.013727..CBCL..","customername":"Lee subdirectories","dynamicid":"223f3423dsf23423423"}],"message":""}';

my $perl = decode_json $json;

print Dumper $perl;

Output:

$VAR1 = {
      'status' => 'success',
      'message' => '',
      'data' => [
                  {
                    'dynamicid' => '2342342332sd32423',
                    'customername' => 'Lee gates',
                    'empid' => '345232'
                  },
                  {
                    'empid' => '36.VLXP.013727..CBCL..',
                    'customername' => 'Lee subdirectories',
                    'dynamicid' => '223f3423dsf23423423'
                  }
                ]
    };

Upvotes: 4

Related Questions