我需要在JSON数组中搜索特定术语并获取包含术语作为键值的数组元素的索引,下面是我正在处理的示例JSON文件,我需要获取“artifact_id”为“jar”的数组元素,所以在这种情况下我需要得到数组的索引1
,“artifact_id”保证是唯一的:
{
"maven": [
{
"version": "1.2",
"artifact_id": "zip"
},
{
"version": "1.2",
"artifact_id": "jar"
}
]
}
我正在使用JSON lib并且可以将JSON解码为Perl对象,任何人都可以为我建议下一步?非常感谢。
my $json_text = do {
open( my $json_fh, "<:encoding(UTF-8)", $filename[0] )
or die("Can't open \$filename\": $!\n");
local $/;
<$json_fh>;
};
my $json = JSON->new;
my $json_data = $json->decode($json_text);
答案 0 :(得分:2)
只需遍历您的数组,并在找到匹配节点后存储索引。下面的例子应该说明一下,但考虑到你的帖子的内容,我想你应该阅读循环,比较运算符以及基本编程。
解码完JSON数据后,毕竟迭代数组并没有什么特别之处;它只是一个数组(给定树的JSON结构参考)。
use JSON qw(decode_json);
my $needle = "jar";
my $needle_location;
my $data = decode_json( join '', <DATA> );
while( my( $idx, $elem ) = each( @{$data->{'maven'}} ) )
{
if( $elem->{'artifact_id'} eq $needle )
{
$needle_location = $idx;
last;
}
}
die "unable to find entry" unless defined $needle_location;
print "needle_location: $needle_location\n";
__DATA__
{
"maven": [
{
"version": "1.2",
"artifact_id": "zip"
},
{
"version": "1.2",
"artifact_id": "jar"
}
]
}
needle_location: 1
答案 1 :(得分:0)
我的答案是基于Filip Roséen - refp的答案,但希望是更先进和缩写的方法:
use Modern::Perl;
use List::Util qw(first);
use JSON qw(decode_json);
my $needle = "jar";
my $data = decode_json do { local $/; <DATA> };
my $needle_location = first( sub {
my $artifact_id = $data->{ maven }->[ $_ ]->{ artifact_id };
defined($artifact_id) && $artifact_id eq $needle
}, 0 .. $#{ $data->{ maven } } ) //
die "unable to find entry";
say "needle_location: $needle_location";
__DATA__
{
"maven": [
{
"version": "1.2",
"artifact_id": "zip"
},
{
"version": "1.2",
"artifact_id": "jar"
}
]
}