Perl脚本来解析JSON数据

时间:2018-06-21 17:56:13

标签: json perl

我正在尝试创建一个脚本来解析JSON内容,但是它不起作用:

#!/usr/local/bin/perl-w
use DBI;
use Parallel::ForkManager;
use LWP::Simple;
use XML::Simple;
use JSON qw( decode_json );
use Data::Dumper;
use DateTime;
use WWW::Mechanize;
use strict;
use warnings;
use JSON;
my $ua = LWP::UserAgent->new();
my $req = new HTTP::Request GET => 'https://google.com/pub/';
my $res = $ua->request($req);
my $contents = $res->content;
##json response:

#{"success":true,"data":"{\"campaign\":\"21490|\",\"format\":\"md5  \",\"delta_timestamp\":\"1528992718\",\"result\":\"success\",\"download_link\":\"https:\\\/\\\/gmail.net\\\/accesskey\\\/getfile\\\/m-spqn-e61-2aef2575a0b5250354f2b0fda033e703?token=HUSYjdC5jyJskXUHiKn13l1A1BaAjH2R&dcma=e8fae90c472ae146\"}","message":null}

print $contents;

#Check the outcome of the Response
if ( $res->is_success ) {
print $res->content;
}


# Decode the main json object
my $jsn = decode_json($res);

# Since 'data' is another serialized object, you need to decode that as well:
my $data = decode_json($jsn);

# Now you can access the contents of 'data'
#want to extract download_link object
print $data->{'download_url'};

我正在查看download_link的内容。

1 个答案:

答案 0 :(得分:3)

use JSON qw(decode_json);

# from $res->content
my $content = '{"success":true,"data":"{\"campaign\":\"21490|\",\"format\":\"md5  \",\"delta_timestamp\":\"1528992718\",\"result\":\"success\",\"download_link\":\"https:\\\/\\\/gmail.net\\\/accesskey\\\/getfile\\\/m-spqn-e61-2aef2575a0b5250354f2b0fda033e703?token=HUSYjdC5jyJskXUHiKn13l1A1BaAjH2R&dcma=e8fae90c472ae146\"}","message":null}';

print decode_json(decode_json($content)->{data})->{download_link};