我的代码段如下,我用谷歌搜索,找不到将变量传递给的解决方案 我带引号的字符串中的发布请求。 大部分google结果只是将纯Json键值字符串对传递给了 发布内容。但是我需要将参数传递给内部Json值部分,并调用相关的REST api。有什么建议么?谢谢!
#!/usr/bin/perl -w
use strict;
use warnings;
# Create a user agent object
use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
$ua->agent("MyApp/0.1");
# Create a request
my $req = HTTP::Request->new(POST => 'https://oapi.dingtalk.com/robot/send?access_token=foofb73f');
$req->content_type('application/json');
my $var1="value from var";
# works fine
my $message = '{"msgtype": "text","text":{"content":"plain string ok"}}';
# failed to compile
# my $message = '{"msgtype": "text","text":{"content":$var1}}';
$req->content($message);
# Pass request to the user agent and get a response back
my $res = $ua->request($req);
# Check the outcome of the response
if ($res->is_success) {
print $res->content;
} else {
print $res->status_line, "n";
}
答案 0 :(得分:0)
您没有正确地将值转换为JSON字符串。
use Cpanel::JSON::XS qw( encode_json );
my $message = encode_json({ msgtype => "text", text => { content => $var1 } });