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

我将 JSON 提供给某个 webhook 以触发通知(M$ 团队)。这很好用。但是,我想扩展我的 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}
        }]
  }]
};

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

回答

您可以推入您在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 dereferenceencing,有些人认为它更易于阅读。

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

有关更多信息,请参阅perlref和perlreftut。


以上是根据条件添加到JSON($payload={})的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>