Home > database >  Mojo::UserAgent response and pretty JSON
Mojo::UserAgent response and pretty JSON

Time:08-12

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

CodePudding user response:

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

CodePudding user response:

I typically don't care if something pretty prints JSON because I'll use jq for that task. Once I get something working, it's rare that I'm looking at the JSON myself, and when I do want to do that, it's easy:

perl script.pl | jq -r .

This way, my program doesn't have to do any extra work, I don't need extra dependencies, and I don't force the pretty JSON version on something that doesn't care about it.

  • Related