Perl LWP将JSON输出作为字符串返回

0tdrvxhp  于 2023-10-24  发布在  Perl
关注(0)|答案(2)|浏览(151)

我正在使用Perl LWP::UserAgent从一个API获得响应。除了一个问题,一切都很好。
我使用的API以JSON格式返回响应。但是当我通过LWP模块获得响应时,我将其作为字符串获得,如下所示。

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

我做了“print Dumper $response“来得到输出。
还有一件事,挑战是,我的客户不想去Perl模块的JSON(使用JSON::Parse 'parse_json';).

6tqwzwtp

6tqwzwtp1#

您需要将JSON字符串解码为Perl数据结构。如果您的perl版本为5.14+,则JSON::PP包含在核心中,因此无需安装。

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;

输出量:

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

ars1skjm2#

Mojolicious通过在响应对象上调用json方法来处理这个问题:

use Mojo::UserAgent;

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

相关问题