1

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";
      }
}
  • 1
    err, decode *is* doing that; it is changing JSON nulls to perl undefs. just test with `defined($v)` – ysth Jun 02 '13 at 21:03
  • Perl handles undef just fine. If your json actually contains a literal, quoted "undef", it's badly broken. – innaM Jun 03 '13 at 04:50

3 Answers3

3

$_ // "" 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";
      }
}
mpapec
  • 50,217
  • 8
  • 67
  • 127
2

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';
  }
}
Borodin
  • 126,100
  • 9
  • 70
  • 144
0

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

or even

$k ||= "empty";
$v ||= "empty";
print "$k => $v\n";
AdrianHHH
  • 13,492
  • 16
  • 50
  • 87
  • 5
    In v10 and later, the defined-or operator `//` can be used. It works like `||` except that it tests for definedness, not truth. This prevents you from changing the legit values `0` (number zero) or `''` (the empty string). On earlier perls, `$x = defined $x ? $x : "empty"` or `$x = "empty" unless defined $x` could be used. – amon Jun 02 '13 at 16:30