在 Perl 的数据参数中使用特殊字符调用 REST API 失败

Calling REST API with special characters in data parameters from Perl is failing

我正在尝试从 perl 调用 servicenow rest api 来更新一些数据属性。

我正在使用 curl 命令来实现此目的,但由于某些原因我无法使用任何可用的 perl 模块。

我能够在 json 的值字段中没有任何特殊字符的情况下成功实现此目的。

以下是用于格式化 cmd 的代码:

my $comments = "b'c";
my $cmd = `curl \"$url\" -i -s --insecure --user test:test --request PUT --header "Accept:application/json" --header "Content-Type:application/json"  --data '{\"comments\":\"$comments\"}'`;

如果上面的值是 "bc" 我能够得到数据,但是如果我给 "b'c" 我得到以下错误:

sh: -c: line 0: unexpected EOF while looking for matching `"'

sh: -c: line 1: syntax error: unexpected end of file

我什至尝试了以下代码:

my $cmd = system "curl https://test.service-now.com/api/now/table/incident/code?sysparm_display_value=true -i -s --insecure --request PUT --header \"Accept:application/json\" --header \"Content-Type:application/json\"  --data '{\"comments\":\"bc\"}' --user test:test";

如果给出带有单引号 b'c 的字符串,我会得到同样的错误。

有人能告诉我如何处理双引号字符串中的单引号吗?

我可以使用

my $comments = "b\"'\"c";

传递给 shell 的字符串是

--data '{"comments":"b'"'"'c"}'

这是三个独立的标记连接在一起:

'{"comments":"b'       resolves to    {"comments":"b
"'"                    resolves to    '
'c"}'                  resolves to    c"}

另见 String::ShellQuote,这是解决此类问题的天赐之物。

use String::ShellQuote;
$comments = "b'c";
@cmd = ("curl", $URL, "-i", "-s", "--insecure", "--request",
        "PUT", "--header", "Accept:applicatin/json", "--header",
        "Content-Type:application/json",
        "--data", qq[{"comments":$comments}], "--user", "test:test");
$cmd = shell_quote(@cmd);
print $cmd;

给你:

curl 'https://test.service-now.com/api/now/table/incident/code?sysparm_display_value=true' 
    -i -s --insecure --request PUT --header 
    Accept:application/json --header Content-Type:application/json 
    --data '{"comments":"b'\''c"}' --user test:test

这也满足 shell 的语法检查器。