in reply to Dynamic Dereferencing

Hi, when trying to access nested elements of data structures using key "paths" as you have, I usually turn to a JSON pointer. I find Mojo::JSON::Pointer easiest to use. In the following demonstration I am being lazy and returning your Dumper dump from a sub and then converting it back to JSON. If you are using LWP::UserAgent's decoded_content() you will already have the structure in $data below.

use v5.014; use JSON; use Mojo::JSON::Pointer; # reconstructing a JSON response from your Dump my $json = to_json( get_response() ); # your client request gets this # converting your API response to a Perl struct my $data = from_json( $json ); # your client should provide this # converting the elements to JSON pointer paths my @elements = map {s!\.!/!gr} (qw/ userName displayName meta.created +/); for my $item ( @{ $data->{Resources} } ) { my $pointer = Mojo::JSON::Pointer->new( $item ); foreach my $element (@elements) { say "$element: " . $pointer->get('/' . $element); } say ''; } sub get_response { return { 'Resources' => [{ 'displayName' => 'User 1', 'userName' => 'user1@test.com', 'id' => '1234567', 'meta' => { 'created' => '2018-04-16T11:5 +7:19.376Z' } }, { 'displayName' => 'User 2', 'userName' => 'user2@test.com', 'id' => '1234568', 'meta' => { 'created' => '2018-04-16T11:5 +9:27.111Z' } }, { 'displayName' => 'User 3', 'userName' => 'user3@test.com', 'id' => '12345679', 'meta' => { 'created' => '2018-11-21T14:4 +9:33.821Z' } }, ], 'totalResults' => 3, 'itemsPerPage' => 50, 'startIndex' => 1, 'schemas' => [ 'urn:ietf:params:scim:api:messages:2.0:ListRe +sponse' ] }; } __END__
Output:
perl 1226873.pl userName: user1@test.com displayName: User 1 meta/created: 2018-04-16T11:57:19.376Z userName: user2@test.com displayName: User 2 meta/created: 2018-04-16T11:59:27.111Z userName: user3@test.com displayName: User 3 meta/created: 2018-11-21T14:49:33.821Z

Hope this helps!


The way forward always starts with a minimal test.

Replies are listed 'Best First'.
Re^2: Dynamic Dereferencing
by Flip76 (Novice) on Dec 07, 2018 at 13:11 UTC
    Thanks a lot for the nice sample!

    One more question:
    # converting the elements to JSON pointer paths my @elements = map {s!\.!/!gr} (qw/ userName displayName meta.created +/);
    qw does not support interpolation right? So I can't use a string there too :-(
    Is there a way around to dynamically change the values there?
    Background: The values are coming from a config-file. So if I add a new entry like "meta.user" in the config, it should work without touching the code...
      Ups sorry, I got it:
      my @elements = map {s!\.!/!gr} (split(' ', $API{$action . '.elements'} +));
      Thanks a lot for your help!