in reply to Parsing the data returned from the companies house API

You are looking at the key when what you want is the value:

foreach my $key (keys %$decodedJSON) { if (is_hashref($key)) { ...

Most likely you wanted:

foreach my $key (keys %$decodedJSON) { my $val = $decodedJSON->{ $key }; if (is_hashref($val)) { ...

Replies are listed 'Best First'.
Re^2: Parsing the data returned from the companies house API
by irtuk (Novice) on Oct 17, 2022 at 14:49 UTC
    Thanks for your quick replies. I have managed to get a little farther, and might be sufficiently well informed to complete this now. I have new code like this:
    use warnings; use strict; use JSON; #use vsutils; use Data::Dumper; use Ref::Util qw(is_arrayref is_hashref); my $companyNumber = 'NF001553'; my $request = "https://api.company-information.service.gov.uk/com +pany/".$companyNumber."/officers"; my $curl = `curl -s --user sameAPIKeyAsBefore:"" $request` || die + "SOMETHING IS WRONG HERE\n"; my $decodedJSON = decode_json($curl) || die "this is not JSON\n"; if (is_hashref($decodedJSON)){ for (sort keys %$decodedJSON) { if ($_ eq 'items'){ print Dumper($decodedJSON->{$_}); } } }
    Now this is returning the directors and their addresses, so I should be able to move forward handling each element.
      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]
        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";} } } } } }