2014-09-24 58 views
0

我想通過使用JSON RPC模塊調用zabbix api host.update。 $ json變量Perl - 在perl中爲zabbix host.update api創建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創建了一個散列數組,併爲散列變量保存了其他信息。

# @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); 

當我運行上面的代碼,我得到了「羣組」

任何一個可以請幫助我的錯誤「不是一個散列引用」?

+0

怎麼樣'groups => \ @ groups'?而且你不必強制串化,即。 '「$ authID」','$ authID'就足夠了。 – 2014-09-24 13:48:27

+0

groups => \ @groups OR groups => \ @groupjson? – 2014-09-24 13:53:16

+0

只是@ @組。你可以一次完成所有的json編碼。 – 2014-09-24 13:54:20

回答

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散列數據,它會被編碼兩次!

+0

太好了。非常感謝..它的工作 – 2014-09-24 15:52:23