gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 02:27:59 28 4
gpt4 key购买 nike

我将 JSON 提供给某个网络钩子(Hook)以触发通知 (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}->@*, ...

参见 perlrefperlreftut获取更多信息。

关于json - 根据条件添加到 JSON ($payload={}),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66152914/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com