PerlMonger79 has asked for the wisdom of the Perl Monks concerning the following question:

Hello,
How can I print specific key and values from a json output with multiple messages? I have the following piece of code
my $resp = $ua->request($req); if ($resp->is_success) { my $output = $resp->decoded_content; use JSON::PP; my $data = join '', $output; my $json = JSON::PP->new->decode($data); # Output 1. use Data::Dump 'dd'; dd $json; # Output 2. foreach my $key ( keys %$json ) { print $key, " => ", $json->{$key},"\n"; } }
#Output 1 { data => [ { mac => "00:04:56:22:51:32", managed_account => "", mode => "ap", name => "Espat AP3", network => "Belize City ePMP", online_duration => 3600, radio => { dl_frame_utilization => 53.50833, dl_kbits => 218936297, dl_pkts => 24533891, dl_retransmits_pct => 3.7125, dl_throughput => 60611.05917, ul_kbits => 11781720, ul_pkts => 10095078, ul_retransmits_pct => 1.7481, ul_throughput => 3261.45, }, sm_count => 49, sm_drops => 1, timestamp => "2022-02-15T04:00:00-06:00", tower => "Espat Twr", type => "epmp", uptime => 3600, }, { mac => "00:04:56:22:51:32", managed_account => "", mode => "ap", name => "Espat AP3", network => "Belize City ePMP", online_duration => 3600, radio => { dl_frame_utilization => 55.79167, dl_kbits => 228622837, dl_pkts => 25268171, dl_retransmits_pct => 3.4875, dl_throughput => 63241.6925, ul_kbits => 11064503, ul_pkts => 10404746, ul_retransmits_pct => 1.6548, ul_throughput => 3060.63917, }, sm_count => 49, sm_drops => 3, timestamp => "2022-02-15T05:00:00-06:00", tower => "Espat Twr", type => "epmp", uptime => 3600, }, ], paging => { limit => 100, offset => 0, total => 25 }, } # Output 2 data => ARRAY(0x2c76ce8) paging => HASH(0x1ee4f28)
I'd like to be able to print out the values for specific keys like... name, dl_kbits, dl_throughput, sm_count, timestamp

I would really appreciate your help. I've gotten a lot of help so far but still I have more ways to go. Thank you.

Replies are listed 'Best First'.
Re: Parsing JSON
by swl (Prior) on Feb 26, 2022 at 03:23 UTC

    You have a nested data structure so need to handle each level appropriately if you are doing it yourself.

    Have a look at the Data Structure Cookbook for more details and other links.

Re: Parsing JSON
by Anonymous Monk on Feb 26, 2022 at 07:49 UTC
      Thank you both for your advice.