【问题标题】:Using Mojo::UserAgent and accessing the JSON in response?使用 Mojo::UserAgent 并访问 JSON 作为响应?
【发布时间】:2020-05-14 11:19:45
【问题描述】:

如何在 mojo 响应中访问 JSON?

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

从 txn 获取 JSON 响应的方法是什么?

【问题讨论】:

    标签: json perl http mojolicious mojo-useragent


    【解决方案1】:

    我能够像这样访问这些数据,

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

    它在result 而不是body

    【讨论】:

    • result 返回实际的响应消息(如果没有响应,则死亡,例如连接或接收响应时出错)。响应消息对象有几个访问器以不同的方式访问消息体,它们最终都作用于body,这是消息体的原始字节字符串:bodytextjsondom。事务对象存储的是这个响应消息和请求消息,而不是这些内容。
    【解决方案2】:

    我的书 Mojolicious Web Clients 中有几个例子,但这是交易。

    当你发出请求时,你会得到一个事务对象:

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

    事务对象同时具有请求和响应(Mojo 与 LWP 甚至其他语言的其他用户代理库的主要特征)。要获得响应,您可以使用resresult 方法。如果由于发生连接错误(ENONETWORK)而无法发出请求,result 会为您而死:

    my $res = $tx->result;
    

    收到回复后,您可以做很多事情(这些都在 Mojo::UserAgent 的 SYNOPIS 部分。如果您想将结果保存到文件中,这很容易:

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

    您可以将内容转换为 DOM 并提取部分 HTML 或 XML:

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

    对于 JSON 响应,您可以将内容提取到 Perl 数据结构中:

    my $data_structure = $res->json;
    

    但是,如果您想要原始 JSON(原始的、未解码的内容主体),那就是请求的消息主体。把它想象成未经过滤的文字:

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

    由于这是响应对象,Mojo::MessageMojo::Message::Response 向您展示了您可以做什么。

    这是一个完整的测试程序:

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

    【讨论】:

    • 此外,$res->json 将为您解码消息(并且还允许您使用 json 指针引用文档中的部分)。在 mojo 应用中,$c->res->json 非常方便。
    猜你喜欢
    • 2019-02-14
    • 1970-01-01
    • 2019-01-20
    • 1970-01-01
    • 2013-03-03
    • 1970-01-01
    • 1970-01-01
    • 2021-12-01
    • 1970-01-01
    相关资源
    最近更新 更多