Reputation: 677
How to submit a valid JSON request using perl mechanize module
I tried
use WWW::Mechanize;
use JSON;
my $mech=WWW::Mechanize->new(
stack_depth => 10,
timeout => 120,
autocheck => 0,
);
$mech->agent_alias( 'Windows Mozilla' );
my $json = '{"jsonrpc":"2.0","id":1,"params":{"query": {"limit":2000,"start":0,"orderBy":[{"columnName":"osName","direction":"Asc"}]},"refresh":true}}';
$url ="http://path/to/url/";
$mech->post($url,$json);
and the result does not come as expected It always parse json error.
So an I doing it right by just posting $mech->post($url,$cjson);
or should I do / add something else?
Upvotes: 0
Views: 2218
Reputation: 20280
Normally one would use the JSON
module so that you can make the data structure in Perl then serialize to a JSON formatted string.
$json_text = encode_json $perl_scalar
which would look something like this:
#!/usr/bin/env perl
use strict;
use warnings;
use JSON qw/encode_json/;
my $data = {
"jsonrpc" => "2.0",
"id" => 1,
"params" => {
"query" => {
"limit" => 2000,
"start" => 0,
"orderBy" => [{
"columnName" => "osName",
"direction" => "Asc",
}],
},
"refresh" => \0,
},
};
print encode_json $data;
Note that \0
and \1
may be used as false and true respectively.
Then again, I haven't used WWW::Mechanize in a long time and I'm not going to dig into the docs, so here is an example using Mojo::UserAgent (more like LWP::UserAgent than mech), which has a built-in JSON handler:
#!/usr/bin/env perl
use strict;
use warnings;
use Mojo::UserAgent;
my $ua = Mojo::UserAgent->new;
my $data = {
"jsonrpc" => "2.0",
"id" => 1,
"params" => {
"query" => {
"limit" => 2000,
"start" => 0,
"orderBy" => [{
"columnName" => "osName",
"direction" => "Asc",
}],
},
"refresh" => \0,
},
};
my $url = "http://path/to/url/";
$ua->post( $url, json => $data );
Upvotes: 2