in reply to Tidy up json from nulls, empty arrays and hashes

>Is there more elegant way to handle it?

The way you have it right now, as a recursive depth first (looks like) traversal of an abritrarily complex data structure, I am going to say no.

$_[0] = undef if (ref $r eq "HASH" && ! %$r) or (ref $r eq "ARRAY" && ! @$r);
The above code is simply the base case of your recursion, what allows it to unwind the call stack.

What is tripping me up is that I have no immediate idea what $$r{$k} is doing - is that some sort of generic reference? Double dollar signs are generally a red flag for me, so I can't really recognize when they might be doing something useful.

Do you have a snippet of JSON to share? I am really curious about your method of traversing the hash. I feel like there is a module on CPAN that allows more idiomatic interactions with your datastructure you call, $json.

Note: I always think myself later when I don't mix up what is $json (a string) and what is the deserialized reference:

my $reference_from_json = JSON->new->allow_nonref->relaxed->decode(do +{ local $/; <STDIN>; }); tidyup_json($refrence_from_json); print JSON->new->pretty->allow_nonref->canonical->encode($reference_fr +om_json);
>Beware that "true" and "false" jsonish data are references to blessed hashes.

Which one, JSON::PP::Boolean? In JSON::PP::Boolean::value_to_json, I see:

elsif( blessed($value) and $value->isa('JSON::PP::Boolean') ) +{ return $$value == 1 ? 'true' : 'false'; }
Indicates to me some implicit recognition of a TO_JSON method that the family of JSON modules support for serializing complex data structures containing blessed references into stringified JSON form.

Replies are listed 'Best First'.
Re^2: Tidy up json from nulls, empty arrays and hashes
by haukex (Archbishop) on May 28, 2020 at 14:28 UTC
    What is tripping me up is that I have no immediate idea what $$r{$k} is doing

    It's the same thing as $r->{$k}; personally I sometimes prefer this style because it's a little bit shorter and my $r = {a=>1}; print $$r{a}; is very similar to my %r = (a=>1); print $r{a};. However, what usually trips people up is that this only works as long as the expression really is that simple (e.g. more complex values than $r), in which case the arrow dereferencing is the cleaner way to go.

Re^2: Tidy up json from nulls, empty arrays and hashes
by Fletch (Bishop) on May 28, 2020 at 13:24 UTC

    Dittos on the $$r{k} looking wrong; reads more clearly to me written as $r->{k} (or if you insist on not using -> then make the dereferencing visually explicit with ${ $r }{ k }).

    Edit: Appeal to authority, but quoth PBP chapter 11 "Wherever possible, dereference with arrows."; I just skimmed the modern PBP videos and didn't find anything explicitly contradicting this so . . .

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.