在 Perl Mojolicious 中呈现 JSON 时防止转义字符

Prevent escape characters when rendering JSON in Perl Mojolicious

我有一个 Mojolicious 控制器调用

$controller->render_to_string(json => { %{$hashref} });
# or
$controller->render_to_string(json => $hashref);

$hashref 包含写入 JSON 对象时被转义的字符。
例如:

my $hashref = {
  path => '/path/to/file'
}

输出为:

{
  "path": "\/path\/to\/file"
}

有没有办法通知 render_to_string() 方法不要 interpolate/escape 这些值?

我应该提一下,实际的字符串是 MD5 哈希值。

渲染 JSON 时,Mojolicious 转义 / 个字符以防止 XSS attacks. This is mentioned in the documentation of Mojo::JSON:

The character / will always be escaped to prevent XSS attacks.

"</script>" -> "<\/script>"

实际上,this is done by Mojo::JSON itself, by opposition to "this is done by Mojolicious automatically every time it renders JSON content". This means that 1) there is no clean way to prevent this behavior when you do ->render( json => ... ), and 2) the fix is simply to use another JSON module to do the encoding, and specify format => 'json' in the call to render (which will cause the headers of the response to contain Content-Type: application/json, as explained in Mojolicious::Guides::Rendering):

use JSON qw( encode_json );

$controller->render(text => encode_json($hashref), format => 'json');

如果您只想使用 $controller->render_to_string 呈现字符串(正如您在问题中所做的那样),那么您可以省略 format => 'json'(无论如何,format is ignored 通过 render_to_string):

use JSON qw( encode_json );

my $json = $controller->render_to_string(text => encode_json($hashref));