I am trying to call a zabbix api host.update by using JSON RPC module. $json variable
$json = {
jsonrpc => '2.0',
method => 'host.update',
params => {
hostid => "$host_id", # global variable from the first function host.get
groups => [
{ groupid => "$arg1" },
{ groupid => "$arg2" },
{ groupid => "$arg3" },
],
},
id => 2,
auth => "$authID",
};
$response = $client->call( $url, $json );
This works fine. But issue is when we have a dynamic list of groupids. It cannot always be 3 groupids.
So i created an array of hash for groupids and also a hash variable to hold other information.
Eg
# @gid is an array of group ids
my @groups; # this array will hold records of hash ie array of hash records
foreach my $id (@gid) {
push( @groups, { groupid => $id } );
# construct array of hash records of groupids
}
my $groupjson = encode_json( \@groups );
my %data = (
jsonrpc => '2.0',
method => 'host.update',
params => { hostid => "@hid", groups => "$groupjson" },
id => 1,
auth => "$authID"
);
my $datajson = encode_json \%data;
$response = $client->call( $api_url, $datajson );
When i run the above code, i get the error "not a hash reference" for "groups"
Can any one pls assist me?
You can do all your json encoding in a single pass, like so:
# shortcut for creating an array of hashes
my @groups = map { { groupid => $_ } } @gid;
my %data = (
jsonrpc => '2.0',
method => 'host.update',
params => {
hostid => \@hid,
groups => \@groups
},
id => 1,
auth => $authID
);
my $json = encode_json( \%data );
If you put data that is already a JSON string into your %data
hash, it will get encoded twice!