× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Use LWP::JSON::Tiny for JSON web APIs in Perl

Michael G Schwern
Mar 05, 2016
<p><a href="https://metacpan.org/pod/LWP">LWP</a> is great way to do web queries in Perl, and combining it with a JSON decoder module you can easily use it to query JSON APIs.  But there's something even easier!</p> <p><a href="https://metacpan.org/pod/LWP::JSON::Tiny">LWP::JSON::Tiny</a> is a subclass of LWP which adds a <code>json_content()</code> method to both the request and the response.  This lets you send and receive JSON without having to fiddle with a JSON library or worry about things like Unicode.  It's taken care of.  Otherwise it works just like LWP.</p> <pre><code>use v5.10; use strict; use warnings; use LWP::UserAgent::JSON; my $ua = LWP::UserAgent::JSON-&gt;new; # Make a POST with JSON in the query my $request = HTTP::Request::JSON-&gt;new( POST =&gt; $url ); $request-&gt;json_content({ stuff =&gt; ["things", "and", "other", "things"] }); my $response = $ua-&gt;request($request); # Read the JSON response into a Perl data structure my $json = $response-&gt;json_content; say "Something: $json-&gt;{something}";</code> </pre>
comments powered by Disqus