【问题标题】:Perl - Creating json object in perl for zabbix host.update apiPerl - 在 perl 中为 zabbix host.update api 创建 json 对象
【发布时间】:2014-09-24 13:45:27
【问题描述】:

我正在尝试使用 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 个 groupid。

所以我为 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 );

当我运行上面的代码时,我得到错误“不是组的哈希引用”

谁能帮帮我?

【问题讨论】:

  • groups => \@groups 怎么样?而且您不必强制字符串化,即。 "$authID"$authID 就够了。
  • 组 => \@groups OR 组 => \@groupjson ?
  • 只是@groups。您可以一次完成所有 json 编码。

标签: json perl zabbix


【解决方案1】:

您可以一次完成所有 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 哈希中,它将被编码两次!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-05
    • 1970-01-01
    • 2013-07-16
    • 2011-03-25
    • 1970-01-01
    • 2014-03-21
    • 1970-01-01
    • 2013-08-29
    相关资源
    最近更新 更多