Search code examples
perlmojo-useragent

Mojo::UserAgent response and pretty JSON


I have the following code which using Mojo::UserAgent to get a json response:

$tx = $ua->get($host.'/api/endpoint/streams' => {Token  => $token , accept => 'application/json' ,'Content-Type' => 'application/json' });

print $tx->res->body;

which return the result as JSON and print it as raw JSON , my question how I can print the results as pretty json


Solution

  • You're printing the response body in the format it came back from the API. This is just a string of JSON that happens to be not indented. To get it to look pretty, you have to decode it into a Perl data structure (you could print it at this point to read it, if that's enough), and then turn it back into JSON with pretty printing enabled.

    Mojo::Message has parsing built in, so you can do this:

    my $streams = $tx->res->json;
    

    If all you want is to read the result, tt this point, you might use Data::Dumper or something nicer to read, like Data::Printer.

    use Data::Dumper;
    print Dumper $streams;
    

    You already have Mojo::JSON as that is used by Mojo::UserAgent, but it doesn't seem to do pretty printing. JSON::PP has been in Perl code since the 5.14 release, so you are likely safe to use that.

    use JSON::PP;
    print JSON::PP->new->utf8->pretty(1)->encode($streams);