【问题标题】:add to JSON ($payload={}) on condition在条件下添加到 JSON ($payload={})
【发布时间】:2021-05-15 02:04:29
【问题描述】:

我将 JSON 提供给一些 webhook 以触发通知 (M$ Teams)。这很好用。但是,我想扩展我的 Perl 脚本:我需要在特定条件下将一个新节点添加到我的“消息卡”构造中

例如我定义了这个:

my $payload={};
$payload = {
    '@type' => 'MessageCard',
    '@context' => 'http://schema.org/extensions',
    themeColor => $event{COLOR},
    text => $event{SERVICEOUTPUT},
    sections => [{
        facts => [{
            name => 'Type',
            value => "$event{NOTIFICATIONTYPE} $event{ADDITIONALINFO}"
        },
        ]
    }],
    potentialAction => [{
        '@type' => "OpenUri",
        name => "View Monitoring",
        targets => [{
            os => "default",
            uri => $naemon_url
        }]
    }]
};

$ua = LWP::UserAgent->new;
my $req = POST($opt_webhook
    , 'Content-Type' => 'application/json; charset=UTF-8'
    , 'Content' => encode_json($payload)
);
my $resp = $ua->request($req);

如果(条件),我想将其扩展如下(顺序很重要):

$payload = {
    '@type' => 'MessageCard',
    '@context' => 'http://schema.org/extensions',
    themeColor => $event{COLOR},
    text => $event{SERVICEOUTPUT},
    sections => [{
        facts => [{
            name => 'Type',
            value => "$event{NOTIFICATIONTYPE} $event{ADDITIONALINFO}"
        },
        ]
    }],
    potentialAction => [{
        '@type' => "OpenUri",
        name => "View Monitoring",
        targets => [{
            os => "default",
            uri => $naemon_url
        }]
    },
    {
        '@type' => "OpenUri",
        name => "Notes (Logs, Docs,..)",
        targets => [{
            os => "default",
            uri => $event{SERVICENOTESURL}
        }]
  }]
};

我不确定如何实现这一点。谁能提供智慧如何解决这个问题?

【问题讨论】:

  • 您是否开启了use strictuse warnings?您的 $ua 未声明。
  • @simbabque 是的,这只是当前代码的摘录

标签: json perl nagios


【解决方案1】:

您可以推入您在potentialAction 键中的数组引用。为此,您需要将其作为数组取消引用

my $payload = {
    '@type' => 'MessageCard',
    potentialAction => [{
        name => "View Monitoring",
        targets => [{
            os => "default",
        }]
    }]
};

if ($maybe) {
    push @{ $payload->{potentialAction} }, {
        name => "Notes (Logs, Docs,..)",
        targets => [{
            os => "default",
        }]
    };
}

如果您的 Perl 版本是 5.24 或更高版本,您还可以使用 postfix dereferencing,有些人觉得它更容易阅读。

push $payload->{potentialAction}->@*, ...

请参阅perlrefperlreftut 了解更多信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多