Aurelia Peters
Aurelia Peters

Reputation: 2209

How to enable "pretty" JSON rendering in Mojolicious::Lite?

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.

Upvotes: 4

Views: 1885

Answers (3)

juj
juj

Reputation: 447

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.

Upvotes: 3

simbabque
simbabque

Reputation: 54333

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/

Upvotes: 2

Chankey Pathak
Chankey Pathak

Reputation: 21676

JSON::PP has pretty method.

$json->pretty([$enable])

Upvotes: 1

Related Questions