json - 在 Perl Mojolicious 中渲染 JSON 时防止转义字符

标签 json perl escaping mojolicious

我有一个可以调用的 Mojolicious Controller

$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() 方法不要插入/转义这些值?

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

最佳答案

渲染 JSON 时,Mojolicious 会转义 / 字符以防止 XSS attacksdocumentation of Mojo::JSON中提到了这一点:

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

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

在实践中,this is doneMojo::JSON 本身,反对“这是 Mojolicious 每次渲染 JSON 内容时自动完成的”。这意味着 1) 当您执行 ->render( json => ... ) 时,没有干净的方法来防止这种行为,2) 修复方法只是使用另一个 JSON 模块来执行编码,并在对 render 的调用中指定 format => 'json' (这将导致响应的 header 包含 Content-Type: application/json,如 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 by render_to_string):

use JSON qw( encode_json );

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

关于json - 在 Perl Mojolicious 中渲染 JSON 时防止转义字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71875318/

相关文章:

multithreading - Perl 线程::共享嵌套数据结构

Perl 打印哈希数组的数组?

python - 使用 decode() 与正则表达式对这个字符串进行转义

java - 如何在Java中验证Instagram实时API x-hub-signature?

android - 使用 Volley 获取 JSONArray

json - 使用 elequent 构建器查询 Laravel 模型中的 Json 属性字段

Java Restful服务响应过滤

string - 在 Perl 中,如何将整个文件读入字符串?

escaping - 如何在 YAML 字符串中转义冒号和其他特殊字符?

asp.net - 自动转义 Asp.Net MVC