Search code examples
jsonperlnullundef

How can I gracefully iterate over a key - value hash generated from JSON containing values set to 'undef' and 'null'?


I am pulling a third party's json response and sometimes the values of the fields are literally 'undef' or 'null'. If I try to do a print of the key and value of each object in this json, whenever there is a undef value it will throw an uninitialized value error.

Is there something I can add to the initial $json->decode to change those null/undefs to something perl can handle? Or maybe even just have it exclude the value pairs that are null/undef from being deposited into $json_text?

my $json_text = $json->decode($content);

foreach my $article(@{$json_text->{data}->{articles}}){
      while (my($k, $v) = each ($article)){
        print "$k => $v\n";
      }
}

Solution

  • $_ // "" will translate undef values to empty string,

    my $json_text = $json->decode($content);
    
    foreach my $article (@{$json_text->{data}->{articles}}) {
          while (my($k, $v) = map { $_ // "" } each %$article) {
            print "$k => $v\n";
          }
    }