我试图通过使用JSON RPC模块调用zabbix api host.update。 $ json变量
$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 );
这很好用。但问题是我们有一个动态的groupid列表。它不能总是3个groupids。
所以我为groupids创建了一个哈希数组,还有一个哈希变量来保存其他信息。
例如
# @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 );
当我运行上面的代码时,我得到错误"而不是哈希引用" for" groups"
任何人都可以帮助我吗?
答案 0 :(得分:2)
您可以一次性完成所有json编码,如下所示:
# 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 );
如果您将已经是JSON字符串的数据放入%data
哈希,它将被编码两次!