首页 > 解决方案 > 转义 JSON 字符串中的特殊字符

问题描述

我有包含变量的 Perl 脚本$env->{'arguments'},这个变量应该包含一个 JSON 对象,我想将该 JSON 对象作为参数传递给我的其他外部脚本并使用反引号运行它。

$env->{'arguments'}转义前的值:

$VAR1 = '{"text":"This is from module and backslash \\ should work too"}';

$env->{'arguments'}转义后的值:

$VAR1 = '"{\\"text\\":\\"This is from module and backslash \\ should work too\\"}"';

代码:

print Dumper($env->{'arguments'});
escapeCharacters(\$env->{'arguments'});
print Dumper($env->{'arguments'});

my $command = './script.pl '.$env->{'arguments'}.'';
my $output = `$command`;

转义字符功能:

sub escapeCharacters
{
    #$env->{'arguments'} =~ s/\\/\\\\"/g;
    $env->{'arguments'} =~ s/"/\\"/g;
    $env->{'arguments'} = '"'.$env->{'arguments'}.'"';
}

我想问你什么是正确的方法以及如何将该 JSON 字符串解析为有效的 JSON 字符串,我可以将其用作我的脚本的参数。

标签: jsonperlescapingcharacter

解决方案


你在重新发明一个轮子

use String::ShellQuote qw( shell_quote );

my $cmd = shell_quote('./script.pl', $env->{arguments});
my $output = `$cmd`;

或者,您可以使用许多 IPC:: 模块来代替qx. 例如,

use IPC::System::Simple qw( capturex );

my $output = capturex('./script.pl', $env->{arguments});

因为您至少有一个参数,所以您还可以使用以下内容:

my $output = '';
open(my $pipe, '-|', './script.pl', $env->{arguments});
while (<$pipe>) {
   $output .= $_;
}

close($pipe);

请注意,当前目录不一定是包含正在执行的脚本的目录。如果要script.pl在与当前执行脚本相同的目录中执行该脚本,则需要进行以下更改:

添加

use FindBin qw( $RealBin );

并更换

'./script.pl'

"$RealBin/script.pl"

推荐阅读