I am using Perl as my web-service.
I have my variables stored in pic1 and pic2 variables.
I want to make an JSON object from that and pass to the client side which is Sencha touch application(print that json object as done in "arch.twitter.com/search.json?q='test'") webservice.
I have done this much.
print header('application/json');
my %data = (img_one => $pic1,img_two => $pic2);
my $json_text = new JSON;
$json_text = to_json(\%data);
print $json_text;
Please guide me in this problem
You didn't specify what kind of modules are you using. CGI? CGI::Simple? Something different?
So I'll just give you very materialistic script to print simple JSON response.
#!/usr/bin/env perl
use strict;
use warnings;
use JSON;
my %data = (img_one => 'pic1', img_two => 'pic2');
print "Content-Type: application/json\n\n";
print to_json \%data;
Related
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.
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};
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';).
Any help would be appreciated!
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'
}
]
};
Here is my code that I try to open the file to get data and change it to UTF-8, then read each line and store it in variable my $abstract_text and send it back in JSON structure.
my $fh;
if (!open($fh, '<:encoding(UTF-8)',$path))
{
returnApplicationError("Cannot read abstract file: $path ($!)\nERRORCODE|111|\n");
}
printJsonHeader;
my #lines = <$fh>;
my $abstract_text = '';
foreach my $line (#lines)
{
$abstract_text .= $line;
}
my $json = encode_json($abstract_text);
close $fh;
print $json;
By using that code, I get this error;
hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)
error message also point out that the problem is in this line;
my $json = encode_json($abstract_text);
I want to send the data back as a string (which is in UTF-8). Please help.
I assume you're using either JSON or JSON::XS.
Both allow for non-reference data, but not via the procedural encode_json routine.
You'll need to use the object-oriented approach:
use strict; # obligatory
use warnings; # obligatory
use JSON::XS;
my $encoder = JSON::XS->new();
$encoder->allow_nonref();
print $encoder->encode('Hello, world.');
# => "Hello, world."
I have tried my script on Mac OS Mavericks (perl 5.16.2) and Yosemite and also with Windows 7 (strawberry-perl-5.20.1.1-64bit-portable).
It is supposed to read UTF-8 data (russian text) and put it into a data structure - and finally print the data structure as JSON string (the output will be used to feed Core Data in an iOS word game).
The first part works (extracting words and printing them - to verify) works well, but the final part not: the resulting JSON string contains garbage:
Does anybody please know, how to fix my simple test script?
#!/usr/bin/perl -w
use strict;
use warnings;
use utf8;
use JSON;
binmode(STDOUT, ':utf8');
my $root = { words => [] };
while (<DATA>) {
chomp;
utf8::decode($_);
my #a = split /\s*[:,]\s*/;
my $words = [];
for my $word (#a[1 .. $#a]) {
print "WORD: $word\n";
#push #$words, utf8::encode($word);
push #$words, $word;
}
push #{$root->{words}}, $words;
}
print to_json($root, {utf8 => 1, pretty => 1});
__DATA__
Голова: небо, язык, мозг, глотка, надгортанник, пищевод, горло, гортань
Сумки: портмоне, кошелек, портфель, рюкзак, лямка, застежка
You're double encoding. You're encoding using from_json (utf8 => 1), then you're encoding again when outputting to STDOUT (binmode(STDOUT, ':utf8');).
The solution isn't clear, because it's not clear what you are trying to achieve. If you're really going to output non-JSON and JSON to STDOUT, don't ask from_json to encode.
The output looks "wrong", but that's OK: it's encoded. To see it correctly, just set
binmode STDOUT, ':raw';
before printing the JSON.
You can simplify the script by using encode_json:
#!/usr/bin/perl
use strict;
use warnings;
use utf8;
use JSON;
binmode(STDIN, ":utf8");
binmode(STDOUT, ":utf8");
my $root;
while (<DATA>) {
chomp;
my #words = split /\s*[:,]\s*/;
push #{ $root->{words} }, [];
for my $word (#words[1 .. $#words]) {
print "WORD: $word\n";
push #{ $root->{words}[-1] }, $word;
}
}
my $json = encode_json($root);
binmode STDOUT, ':raw';
print $json;
I'm trying to edit an old perl script and I'm a complete beginner. The request from the server returns as:
$VAR1 = [
{
'keywords' => [
'bare knuckle boxing',
'support group',
'dual identity',
'nihilism',
'support',
'rage and hate',
'insomnia',
'boxing',
'underground fighting'
],
}
];
How can I parse this JSON string to grab:
$keywords = "bare knuckle boxing,support group,dual identity,nihilism,support,rage and hate,insomnia,boxing,underground fighting"
Full perl code
#!/usr/bin/perl
use LWP::Simple; # From CPAN
use JSON qw( decode_json ); # From CPAN
use Data::Dumper; # Perl core module
use strict; # Good practice
use warnings; # Good practice
use WWW::TheMovieDB::Search;
use utf8::all;
use Encode;
use JSON::Parse 'json_to_perl';
use JSON::Any;
use JSON;
my $api = new WWW::TheMovieDB::Search('APIKEY');
my $img = $api->type('json');
$img = $api->Movie_imdbLookup('tt0137523');
my $decoded_json = decode_json( encode("utf8", $img) );
print Dumper $decoded_json;
Thanks.
Based on comments and on your recent edit, I would say that what you are asking is how to navigate a perl data structure, contained in the variable $decoded_json.
my $keywords = join ",", #{ $decoded_json->[0]{'keywords'} };
say qq{ #{ $arrayref->[0]->{'keywords'} } };
As TLP pointed out, all you've shown is a combination of perl arrays/hashes. But you should look at the JSON.pm documentation, if you have a JSON string.
The result you present is similar to json, but the Perl-variant of it. (ie => instead of : etc). I don't think you need to look into the json part of it, As you already got the data. You just need to use Perl to join the data into a text string.
Just to eleborate on the solution to vol7ron :
#get a reference to the list of keywords
my $keywords_list = $decoded_json->[0]{'keywords'};
#merge this list with commas
my $keywords = join(',', #$keywords_list );
print $keywords;