Search code examples
jsonperlperl-modulelwplwp-useragent

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';).


Solution

  • 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'
                      }
                    ]
        };