0

I am trying to create a script to parse JSON content but it is not working:

#!/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'};

I am looking at the content of download_link.

4
  • You should actually print out your object and ensure it matches the form you think it does. Just glancing at the commented out object it would suggest that your variable $data doesn't have a key "download_url". Commented Jun 21, 2018 at 18:00
  • 2
    $res is an HTTP::Response object, not a JSON string! Commented Jun 21, 2018 at 18:16
  • Your question is not clear/poorly phrased (I have edited it). You are not showing your current errors. You speak about "download_link" but your code uses "download_url". Your script starts with "perl-w" which is probably a typo for "perl -w" and in which case the -w is useless as you have use warnings; (as recommended) below. Commented Jun 21, 2018 at 19:23
  • Do NOT use this form: new HTTP::Request, use instead HTTP::Request->new() Commented Jun 21, 2018 at 19:25

1 Answer 1

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};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.