在Perl Mojolicious中渲染JSON时,请防止逃生角色
我有一个莫约利奇的控制器,该控制器调用
$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哈希。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当渲染JSON时,Mojolicious Escapes
/
字符以防止。这在实际上,这是通过
):
>完成的
Mojo :: JSON
本身,反对“这是由每次渲染JSON内容自动完成的”。这意味着1)当您执行- > Render(json => ...)
和2)修复程序仅使用另一个JSON模块时,没有干净的方法来防止此行为进行编码,并指定格式=> 'json'
在调用Render
(这会导致响应的标题包含content-type:application/json
,如mojolicious :: guides :: guides :: guendering :: Rendering
如果您只想将
$ controller-> render_to_string
渲染到字符串(就像您在问题中所做的那样),则可以省略form> format => 'json'
(无论如何,格式
render_to_string ):When rendering JSON, Mojolicious escapes
/
characters to prevent XSS attacks. This is mentioned in the documentation ofMojo::JSON
:In practice, 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 specifyformat => 'json'
in the call torender
(which will cause the headers of the response to containContent-Type: application/json
, as explained inMojolicious::Guides::Rendering
):If you just want to render to a string with
$controller->render_to_string
(as you've done in your question), then you can omitformat => 'json'
(anyways,format
is ignored byrender_to_string
):