in reply to Obtain the full path of a json key

Short and sweet :)

#!/usr/bin/perl use strict; # https://perlmonks.org/?node_id=11165436 use warnings; use Path::Tiny; use JSON::PP; sub names { my ($data) = @_; if( 'ARRAY' eq ref $data ) { map names($_), @$data; } elsif( 'HASH' eq ref $data ) { map { my $id = $_; map "$id.$_", names($data->{$_}) } keys %$data; } else { "\n" } } print s/\.$//r for names decode_json path('d.11165436')->slurp; # FIXM +E filename

Outputs:

Obj1.Obj11Id Obj1.Obj11Attributes.Obj11AttributesObj2.Obj11AttributesObj2Key1 Obj1.Obj11Attributes.Obj11AttributesObj1.Obj11AttributesObj1Key1 Obj1.Obj11Attributes.Obj11AttributesObj1.Obj11AttributesObj1Key2 Obj1.Obj11Version Obj1.Obj12Attributes.Obj12AttributesArray1.Obj12AttributesArray1Obj1Ke +y1 Obj1.Obj12Attributes.Obj12AttributesObj2.Obj12AttributesObj2Key1 Obj1.Obj12Attributes.Obj12AttributesObj1.Obj12AttributesObj1Key2 Obj1.Obj12Attributes.Obj12AttributesObj1.Obj12AttributesObj1Key1 Obj1.Obj12Version Obj1.Obj12Id Obj2.Obj21Attributes.Obj21AttributesObj2.Obj21AttributesObj2Key1 Obj2.Obj21Attributes.Obj21AttributesObj1.Obj21AttributesObj1Key2 Obj2.Obj21Attributes.Obj21AttributesObj1.Obj21AttributesObj1Key1 Obj2.Obj21Version Obj2.Obj21Id Obj2.Obj22Version Obj2.Obj22Attributes.Obj22AttributesArray1.Obj22AttributesArray1Obj1Ke +y1 Obj2.Obj22Attributes.Obj22AttributesObj2.Obj22AttributesObj2Key1 Obj2.Obj22Attributes.Obj22AttributesObj1.Obj22AttributesObj1Key2 Obj2.Obj22Attributes.Obj22AttributesObj1.Obj22AttributesObj1Key1 Obj2.Obj22Id

Replies are listed 'Best First'.
Re^2: Obtain the full path of a json key
by Anonymous Monk on Jun 23, 2025 at 13:40 UTC
    Thank you all for the contributions, I'm installing the missing package Path::Tiny to try all them :)

      You don't really need Path::Tiny. If I didn't have it, I would have done something like this using just standard perl:

      #!/usr/bin/perl use strict; # https://perlmonks.org/?node_id=11165436 use warnings; use JSON::PP; sub names { my ($data) = @_; if( 'ARRAY' eq ref $data ) { map names($_), @$data; } elsif( 'HASH' eq ref $data ) { map { my $id = $_; map "$id.$_", names($data->{$_}) } keys %$data; } else { "\n" } } @ARGV or @ARGV = 'd.11165436.json'; # FIXME filename print map s/\.$//r, names decode_json join '', <>;

      This would allow you to put the JSON file name on the command line, or if you didn't put any arguments on the command line, would run the program against a test file.