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

StackOverflow https://stackoverflow.com/questions/16884412

  •  30-05-2022
  •  | 
  •  

Domanda

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";
      }
}
È stato utile?

Soluzione

$_ // "" 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";
      }
}

Altri suggerimenti

Since you are running a version of Perl that allows each to be applied to a hash reference, you can also use the defined-or operator //.

An expression like a // b evaluates to a if a is defined, otherwise b.

You can use it like this.

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

for my $article (@{$json_text->{data}{articles}}) {
  while (my ($k, $v) = each $article) {
    printf "%s => %s\n", $k, $v // 'null';
  }
}

Try printf "%s => %s\n", $k || "empty", $v || "empty";

or even

$k ||= "empty";
$v ||= "empty";
print "$k => $v\n";
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top