根据条件添加到 JSON ($payload={})

add to JSON ($payload={}) on condition

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

例如我这样定义:

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}
        }]
  }]
};

我不确定如何实现。任何人都可以提供智慧如何解决这个问题吗?

您可以将 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}->@*, ...

有关详细信息,请参阅 perlref and perlreftut