Perl JSON - 在记录结果之前检查值是否存在

问题描述 投票:-1回答:2

如果key = tls,dns或http,我试图从以下json输出中提取doc_count值。

JSON:https://pastebin.com/T5Cu3w79

到目前为止,我已经尝试打印出“key”的值,但我无法让它返回结果。 $ hash是存储为数组的JSON输出。

my @buckets = @{ $hash->{'buckets'} };
foreach my $proto (@buckets) {
    print $proto->{"key"} . "\n";
}

编辑:在这里查看JSON文件:https://pastebin.com/T5Cu3w79。我想要的信息是从第818行到第859行的“key”和“doc_count”值。

json perl
2个回答
-1
投票

鉴于您的pastebin数据结构(看起来实际上是一个解码的JSON结构),您在第818行开始指定的“buckets”数组可以使用其散列键来访问,如下所示:

my $buckets = $hash->{'spi'}->{'prot-term'}->{'buckets'}; 
for my $proto (@$buckets) {
    # access proto->{'key'}, $proto->{'doc_count'}
} 

如果你想要所有“桶”数组,假设“桶”数组总是在$hash的第三层:

for my $l1 (keys %$hash) {
    for my $l2 (keys %{$hash->{$l1}}) {
        my $buckets = $hash->{$l1}->{$l2}->{'buckets'};
        for my $proto (@$buckets) {
            # $proto->{'key'}, $proto->{'doc_count'}
        }
    }
}

0
投票

鉴于你的最后一句,这似乎做你需要的。

use strict;
use warnings;

use List::Util qw( sum );
# Existing code to build the hash with buckets ...
my @buckets = @{ $hash->{buckets} };
my %count_keys = (
        tls => 1,
        dns => 1,
        http => 1,
    ); # lookup: which keys do I count
my %doc_count;

for my $proto ( @buckets ){
    my $key = $proto->{key};
    next unless $count_keys{ $key }; # not to be counted: skip this
    $doc_count{ $key }+= $proto->{doc_count}; # counting per type
}

print "$_: $doc_count{$_}\n" for sort keys(%doc_count); # output count per type
print "overall: " . sum(values(%doc_count)); # count of all doc counts

不过,我不确定是否还有其他问题/问题:你有解码JSON吗?如果你有更多的代码继续下去会更有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.