Reputation: 13
I am trying to access data returned from an api, I just cant get the correct values out of the array, I know that the API is returning data as Dumper can print it out on screen no problem.
When trying to print all information about the array so I know exactly what to print out I am just receiving a hash. Sorry if this is confusing, still learning.
Using the following code I am getting the below output,
foreach my $hash (@{$res->data}) {
foreach my $key (keys %{$hash}) {
print $key, " -> ", $hash->{$key}, "\n";
}
}
Output
stat -> HASH(0xf6d7a0)
gen_info -> HASH(0xb66990)
Do any of you know how I can modify the above to traverse in the HASHes?
The bottom line of what I am trying to do is print out a certain value for the array.
Please see my Dumper of the array.
print Dumper(\$res->data);
http://pastebin.com/raw.php?i=1deJZX2f
The data i am trying to print out is the guid field.
I thought it would be something like
print $res->data->[1]->{guid}
But this doesn't seem to work, i'm sure i'm just missing something here and thinking more about it than i should, if somebody could point me in the write direction or write me the correct print and explain what I was doing wrong that would be great
Thank You
Upvotes: 1
Views: 97
Reputation: 1177
The structure you have is a an array of hashes of hashes. This is shown in the dump as
# first hash with key being 'stat',
# Second hash as keys (traffic, mail_resps...) followed by values (=> 0)
'stat' => {
'traffic' => '0', .
'mail_resps' => '0',
so the value of the keys in the first hash is a hash or a hash of hashes.
If you want to print out every element, you need to add an additional loop for the keys of the second hash.
foreach my $hash (@{$res->data}) { # For each item in the array/list
foreach my $key (keys %{$hash}) { # Get the keys for the first hash (stat,gen_info)
foreach my $secondKey ( keys %{$hash->{$key}}) # Get the keys for the second hash
{
print $key, " -> ", $secondKey, " -> ",${$hash->{$key}}{$secondKey}, "\n";
}
}
}
If you are just interested in the guid, then you would access it as:
$res->data->[1]->{gen_info}{guid}
where gen_info is the key for the first hash and the guid is the key for the second hash
You can check to see if the keys exists in the first and second hash before access using exits
$n = 1 # Index of the array you want to get the information
if (( exists $res->data->[$n]->{gen_info} ) && # Check for the keys to exists in
( exists $res->data->[$n]->{gen_info}{guid} )) # in each hash
{
# do what you need to
}
else
{
print "ERROR: either gen_info or guid does not exist\n";
}
Upvotes: 1
Reputation: 4294
If there is a hash in a hash , you could try this
foreach my $hash (@{$res->data}) {
foreach my $key (keys %{$hash}) {
my $innerhash = $hash->{$key};
print $key . " -> " . $hash . "\n";
foreach my $innerkey (keys %{$innerhash}) {
print $key. " -> " . $innerhash->{$innerkey}. "\n";
}
}
}
Upvotes: 2