我有一个迷人的控制器

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

The $hashref contains characters that are being escaped when written to the JSON object.
For example:

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

输出为:

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

有没有办法通知render_to_string()方法不要插值/转义这些值?

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

推荐答案

在呈现JSON时,Mojolicious会转义/个字符以防止XSS attacks个字符.这在documentation of Mojo::JSON中提到:

角色/将始终转义以防止XSS攻击.

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

实际上,this is doneMojo::JSON本身,与"Mojolicious每次呈现JSON内容时都会自动完成"相反.这意味着1)在执行->render( json => ... )时,没有干净的方法来防止这种行为,2)修复方法只是使用另一个JSON模块来进行编码,并在对render的调用中指定format => 'json'(这将导致响应的头包含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 x render_to_string):

use JSON qw( encode_json );

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

Json相关问答推荐

在ConvertFrom-Json之后需要从PowerShell对象中获取数据

在MongoDB中检索某个月份和年份的JSON文档

如何使用模式注册中心创建从主题中取消本地化的ks qlDB表?

使用Kotlin限制序列化类属性的允许整数值

使用JQ合并JSON列表中的对象

json 字符串到 Postgres 14 中的表视图

颠簸转换问题

将来自 Golang 的 JSON API 调用响应输出到 nextjs 前端

golang递归json来构造?

如何将该 JSON 解析为 Kotlin 类?

如何在 Android Studio 中将 List 字段作为空列表[]返回?

jq:来自嵌套 JSON 的映射

N1QL 聚合查询 Couchbase

如何使用 LINQ 在 C# 中重构对象?

Play Framework:如何序列化/反序列化与 JSON 的枚举

Newtonsoft Json 将值 {null} 转换为类型System.Int32时出错

json和空数组

在 React 中访问子级的父级状态

无法将空值放入 JSON 对象

Laravel 5 控制器将 JSON 整数作为字符串发送