in reply to Re^2: Parsing the data returned from the companies house API
in thread Parsing the data returned from the companies house API

In fact, you don't need to iterate over hash keys to find out whether a key exists. There is a more effective way to do it: use exists.
my $decodedJSON = decode_json($curl) or die "this is not JSON\n"; if (is_hashref($decodedJSON)) { if (exists $decodedJSON->{items}) { for my $item (@{ $decodedJSON->{items} }) { .... } } }
map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]

Replies are listed 'Best First'.
Re^4: Parsing the data returned from the companies house API
by irtuk (Novice) on Oct 17, 2022 at 15:55 UTC
    Brilliant, thanks so much for the help. For anyone else who wants to parse companies house API for officer and director data this code now does exactly what I want:
    use warnings; use strict; use JSON; use Data::Dumper; use Ref::Util qw(is_arrayref is_hashref); my $companyNumber = 'NF001553'; my $request = "https://api.company-information.service.gov.uk/company +/".$companyNumber."/officers"; my $curl = `curl -s --user youwillneedtoreplacethiswithyourapikey:"" +$request` || die "Problem with CURL call\n"; my $decodedJSON = decode_json($curl) or die "this is not JSON\n"; if (is_hashref($decodedJSON)) { if (exists $decodedJSON->{items}) { for my $item (@{ $decodedJSON->{items} }) { if (exists $item->{name}) { print $item->{name}."\n"; } if (exists $item->{address}){ if (is_hashref($item->{address})){ if (exists $item->{address}->{address_line_1}) +{ print $item->{address}->{address_line_1}."\n";} if (exists $item->{address}->{address_line_2}) +{ print $item->{address}->{address_line_2}."\n";} if (exists $item->{address}->{locality}){ prin +t $item->{address}->{locality}."\n";} if (exists $item->{address}->{region}){ print +$item->{address}->{region}."\n";} if (exists $item->{address}->{postal_code}){ p +rint $item->{address}->{postal_code}."\n";} } } } } }
      Which can be shortened and made less repetitive like this:
      use feature qw{ say }; if (is_hashref($decodedJSON) && exists $decodedJSON->{items}) { for my $item (@{ $decodedJSON->{items} }) { say $item->{name} if exists $item->{name}; if (exists $item->{address} && is_hashref($item->{address})) { for my $key ( qw( address_line_1 address_line_2 locality region post +al_code ) ) { say $item->{address}{$key} if exists $item->{address}{ +$key}; } } } }

      map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]