Simple question. How do I turn on "pretty" json rendering in Mojolicious::Lite? I'm developing a RESTful API and would like to see my output in a bit more human readable format.
3 Answers
You could override the default JSON renderer in the startup method.
For a minimal example:
use JSON::XS;
our $json = JSON::XS->new->utf8->pretty;
sub startup {
my $self = shift;
...
$self->app->renderer->add_handler(json => sub {
${$_[2]} = $json->encode($_[3]{json});
});
}
The default handler is defined in Mojolicious/Renderer.pm and use Mojo::JSON::encode_json
.

- 451
- 3
- 7
-
I just tried this and it didn't work, for the record. The renderer didn't seem to change. This worked: https://gist.github.com/brianmed/3f3e47c1fb9dddd840f3f7e9a17cc53b – AmbroseChapel Oct 24 '22 at 20:20
Mojo::JSON claims to be a minimalistic JSON implementation that is complete to the RFC. It does not implement auto-indentation/making the output pretty.
Your best bet is to use a browser (or other client) that supports that, like SoapUI. There are browser-plugins like JSONView for Chrome.
You can also roll your own client and use one of the JSON implementations, like JSON::MaybeXS.
Then there is also the command line utility json_pp
that comes with the JSON module. It will by default pretty-print. You can pipe the output of curl to it like this:
$ curl -s -H "Accept: application/json" http://www.json-generator.com/api/json/get/ckUMuWrjLS?indent=0 -- | json_pp
The -s
option to curl will silence it's status outputs.
Source of JSON above: http://www.json-generator.com/

- 53,749
- 8
- 73
- 136
JSON::PP has pretty
method.
$json->pretty([$enable])

- 21,187
- 12
- 85
- 133
-
-
None but you could use them, right? See an example here: https://gist.github.com/minty/4051592 – Chankey Pathak Jul 17 '15 at 22:20