Search code examples
jsonperlapilwp

How do I get data from a web API?


I'm pretty basic at Perl, and I need to make a project for my university.

I want to download data from certain link, it is JSON data, so I know I have to use JSON::Parse module from CPAN.

But how to download content of link to my Perl variable? Should I use LWP get()?


Solution

  • Aren't you supposed to be learning Perl if it's a university project?

    Anyway, your program will look something like this. It uses the LWP::Simple module to fetch the JSON data, and then JSON::Parse to process it into a Perl data structure

    I've used printed the author value from each item of the array, as requested in your comment

    use strict;
    use warnings 'all';
    
    use LWP::Simple 'get';
    use JSON::Parse 'parse_json';
    
    use constant URL => 'http://a.wykop.pl/observatory/entries/appkey,dJ4w7fXYpL';
    
    my $json = get URL or die "Unable to get JSON data";
    my $data = parse_json($json);
    
    print "Authors:\n";
    print "  $_->{author}\n" for @$data;
    

    output

    Authors:
      Snurq
      AferaZaAfera
      Devest
      igorsped
      Matt23
      labla
      poprawnie-niepoprawny
      Parkero
      Speed666
      Xune
      Gasior9
      mikolajeq
      Aztek2201
      blogerbezbloga
      Pan_wons
      PanKaczucha
      NieznanyAleAmbitny
      dzika_kaczka_bez_dzioba
      ilili
      Bager
      bmbcz01
      hydrocyfolumpus
      acarter
      Doctor_Manhattan
      strumienzgor