POST request with REST::Client - json

I am creating a POST request using REST::Client and keep getting following error:
Response:Not a SCALAR reference at /nethome/perl5/lib/perl5//LWP/Protocol/http.pm line 254, <IFH> line 1.
My code Snippet:
use warnings;
use diagnostics;
use strict;
use JSON::MaybeXS;
use REST::Client;
my $host = 'myurl';
my $hashref = {};
my $jsonEncode=JSON::MaybeXS->new->utf8(1)->pretty(1);
Inside a Subroutine, using while loop
my #fields=split("\t",$_);
my $sample_id=$fields[0];
my $chr=$fields[1];
my $position=$fields[2];
my $alt=$fields[5];
my $hashref =("variant_request"=>{"searchParameters"=>{"sampleIds"=> ["$sample_id"],"genome"=>[{"loci"=>{"chromosome"=>"$chr","position"=>$position,"allele"=>"$alt"}}]}});
push (#meta,\%hashref);
printQuery (#meta,$encoded);
Inside PrintQuery Subroutine:
my $filename =$_[1];
my $hash = $jsonEncode->canonical->encode($_[0]);
$client->POST($hash,{'Content-Type'=>'application/json','Accept'=>'application/json'});
print 'Response:'.$client->responseContent()."\n";
print 'Response Status:'. $client->responseCode()."\n";
Input:
601 1 114872280 rs544699256 A G

So not exactly sure why this worked:
Changed This:
my $client=REST::Client->new(host=>$host);
To:
my $client=REST::Client->new();
Added:
my $url = 'myurl';
And Finally changed:
$client->POST($url,$jsonrequest,{'Content-Type'=>'application/json','Accept'=>'application/json'});

Related

How do I use encode_json with string in Perl?

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."

how to decode json in perl if value has \n or more than one line

how to decode the json file if a value has more than one line
a.json file:
{
"sv1" : {
"output" : "Hostname: abcd
asdkfasfjsl",
"exp_result" : "xyz"
}
}
when I try to read the above json file, I am hitting with an error "invalid character encountered while parsing JSON string, at character offset 50 (before "\n ...")"
code to read the above json file:
#!/volume/perl/bin/perl -w
use strict;
use warnings;
use JSON;
local $/;
open(AA,"<a.json") or die "can't open json file : $!\n";
my $json = <AA>;
my $data = decode_json($json);
print "reading output $data->{'sv1'}->{'output'}\n";
print "reading output $data->{'sv1'}->{'exp_result'}\n";
close AA;
Besides from whether the JSON is valid or not (see comments on question), you're reading only the first line from the file.
my $json = <AA>;
This is a scalar variable and receives only one line.
Use an array to get all lines:
my #json = <AA>;
my $json = join "\n", #json;
or even better: use File::Slurp::read_file to get the whole content of the file with one simple command.
use File::Slurp qw/read_file/;
my $json = read_file( "a.json" );

Pretty Printer perl module not working as expected

I'm trying to follow the example in the synopsis of HTML::PrettyPrinter. I corrected the typo to create a FileHandle:
my $fh = new FileHandle ">E:\\test.html";
Now the file gets created but I'm getting another error:
Can't call method "isa" on an undefined value at C:/Strawberry/perl/site/lib/HTML/PrettyPrinter.pm line 414.
Here is the code I have so far:
use HTML::TreeBuilder;
# generate a HTML syntax tree
my $tree = new HTML::TreeBuilder;
$tree->parse_file("E:\\file.html");
# modify the tree if you want
use HTML::PrettyPrinter;
my $hpp = new HTML::PrettyPrinter ('linelength' => 130,'quote_attr' => 1);
# configure
$hpp->set_force_nl(1,qw(body head)); # for tags
$hpp->set_force_nl(1,qw(#SECTIONS)); # as above
$hpp->set_nl_inside(0,'default!'); # for all tags
# format the source
my $linearray_ref = $hpp->format($tree);
print #$linearray_ref;
# alternative: print directly to filehandle
use FileHandle;
my $fh = new FileHandle ">E:\\test.html";
if (defined $fh) {
$hpp->select($fh);
$hpp->format();
undef $fh;
$hpp->select(undef),
}
This line is causing the error:
$hpp->format();
HTML::PrettyPrinter::format attempts to call isa on the first argument:
411 sub format {
412 my ($self, $element, $indent, $lar) = #_;
413 # $lar = line array ref
414 confess "Need an HTML::Element" unless $element->isa('HTML::Element');
...
Which causes the error you're getting if it is undef. Passing $tree (which isa HTML::Element) as the first argument populates the file correctly:
$hpp->format($tree);

Parsing JSON Data::Dumper output array in Perl

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;

How to convert a simple hash to json in Perl?

I'm using the following code to encode a simple hash
use JSON;
my $name = "test";
my $type = "A";
my $data = "1.1.1.1";
my $ttl = 84600;
#rec_hash = ('name'=>$name, 'type'=>$type,'data'=>$data,'ttl'=>$ttl);
but I get the following error:
hash- or arrayref expected <not a simple scalar, use allow_nonref to allow this>
Your code seems to be missing some significant chunks, so let's add in the missing bits (I'll make some assumptions here) and fix things as we go.
Add missing boilerplate.
#!/usr/bin/perl
use strict;
use warnings;
use JSON;
my $name = "test";
my $type = "A";
my $data = "1.1.1.1";
my $ttl = 84600;
Make the hash a hash and not an array and don't forget to localise it: my %
my %rec_hash = ('name'=>$name, 'type'=>$type,'data'=>$data,'ttl'=>$ttl);
Actually use the encode_json method (passing it a hashref):
my $json = encode_json \%rec_hash;
Output the result:
print $json;
And that works as I would expect without errors.
Try %rec_hash = ... instead. # indicates a list/array, while % indicates a hash.