首页 > 解决方案 > 解析 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

标签: jsonperl

解决方案


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};

推荐阅读