Evan Carroll
Evan Carroll

Reputation: 1

How can I get access to JSON in a Mojo::UserAgent response?

How can I get access to JSON in a mojo response?

$txn = $ua->post( $url, $headers, json => {json} )

What's the way to get the JSON response from the txn?

Upvotes: 5

Views: 1632

Answers (2)

brian d foy
brian d foy

Reputation: 132918

I have several examples in my book Mojolicious Web Clients, but here's the deal.

When you make a request, you get back a transaction object:

my $ua = Mojo::UserAgent->new;
my $tx = $ua->post( ... );

The transaction object has both the request and response (a major feature that distinguishes Mojo from LWP and even other user agent libraries in other languages). To get the response, you can use the res or result methods. The result dies for you if it couldn't make the request because a connection error occurred (ENONETWORK):

my $res = $tx->result;

Once you have the response, there are various things you can do (and these are in the SYNOPIS section of the Mojo::UserAgent. If you want to save the result to a file, that's easy:

$res->save_to( 'some.json' );

You can turn the content into a DOM and extract parts of HTML or XML:

my @links = $res->dom->find( 'a' )->map( attr => 'href' )->each;

For a JSON response, you can extract the contents into a Perl data structure:

my $data_structure = $res->json;

However, if you wanted the raw JSON (the raw, undecoded content body), that's the message body of the request. Think of that like the literal, unfiltered text:

use Mojo::JSON qw(decode_json);
my $raw = $res->body;
my $data_strcuture = decode_json( $raw );

Since this is the response object, Mojo::Message and Mojo::Message::Response show you what you can do.

Here's a complete test program:

#!perl
use v5.12;
use warnings;

use utf8;

use Mojo::JSON qw(decode_json);
use Mojo::UserAgent;
use Mojo::Util qw(dumper);

my $ua = Mojo::UserAgent->new;

my $tx = $ua->get(
    'http://httpbin.org/get',
    form => {
        name => 'My résumé'
        },
    );

die "Unsuccessful request" 
    unless eval { $tx->result->is_success };

my $data_structure = $tx->res->json;
say dumper( $data_structure );

my $raw = $tx->res->body;
say $raw;

my $decoded = decode_json( $raw );
say dumper( $decoded );

Upvotes: 10

Evan Carroll
Evan Carroll

Reputation: 1

I was able to get access to this data like this,

my $api_order = $tx_cart->result->json->{data};

It's in result not in body.

Upvotes: 1

Related Questions