Home > other >  Prevent escape characters when rendering JSON in Perl Mojolicious
Prevent escape characters when rendering JSON in Perl Mojolicious

Time:04-16

I have a Mojolicious controller that calls

$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'
}

Which are being output as:

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

Is there a way to inform the render_to_string() method not to interpolate/escape these values?

I should mention that the actual strings are MD5 hashes.

CodePudding user response:

When rendering JSON, Mojolicious escapes / characters to prevent XSS attacks. This is mentioned in the documentation of Mojo::JSON:

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

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

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 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');

If you just want to render to a string with $controller->render_to_string (as you've done in your question), then you can omit format => 'json' (anyways, format is ignored by render_to_string):

use JSON qw( encode_json );

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