json - 在 Perl 中解析 JSON 数据
问题描述
我正在解析.json
文件中的 JSON 数据。这里我有 2 种格式的 JSON 数据文件。
我可以解析第一个 JSON 文件 - 文件如下所示:
file1.json
{
"sequence" : [ {
"type" : "type_value",
"attribute" : {
"att1" : "att1_val",
"att2" : "att2_val",
"att3" : "att3_val",
"att_id" : "1"
}
} ],
"current" : 0,
"next" : 1
}
这是我的脚本:
#/usr/lib/perl
use strict;
use warnings;
use Data::Dumper;
use JSON;
my $filename = $ARGV[0]; #Pass json file as an argument
print "FILE:$filename\n";
my $json_text = do {
open(my $json_fh, "<:encoding(UTF-8)", $filename)
or die("Can't open \$filename\": $!\n");
local $/;
<$json_fh>
};
my $json = JSON->new;
my $data = $json->decode($json_text);
my $aref = $data->{sequence};
my %Hash;
for my $element (@$aref) {
my $a = $element->{attribute};
next if(!$a);
my $aNo = $a->{att_id};
$Hash{$aNo}{'att1'} = $a->{att1};
$Hash{$aNo}{'att2'} = $a->{att2};
$Hash{$aNo}{'att3'} = $a->{att3};
}
print Dumper \%Hash;
一切都存储在%Hash
其中,当我打印 Dumper 时,%Hash
我得到以下结果。
$VAR1 = {
'1' => {
'att1' => 'att1_val',
'att2' => 'att2_val',
'att3' => 'att3_val'
}
};
但是当我解析第二组 JSON 文件时,我使用上面的脚本得到了空哈希。输出:
$VAR1 = {};
这是 JSON 文件 -
file2.json
{
"sequence" : [ {
"type" : "loop",
"quantity" : 8,
"currentIteration" : 0,
"sequence" : [ {
"type" : "type_value",
"attribute" : {
"att1" : "att1_val",
"att2" : "att2_val",
"att3" : "att3_val",
"att_id" : "1"
}
} ]
} ]
}
我们可以sequence
在上面的 JSON 数据文件中看到两个,这是导致问题的原因。有人可以告诉我脚本中缺少什么以便解析file2.json
。
解决方案
一种可能是检查type
字段以区分两种文件格式:
# [...]
for my $element (@$aref) {
if ( $element->{type} eq "loop" ) {
my $aref2 = $element->{sequence};
for my $element2 ( @$aref2 ) {
get_attrs( $element2, \%Hash );
}
}
else {
get_attrs( $element, \%Hash );
}
}
sub get_attrs {
my ( $element, $hash ) = @_;
my $a = $element->{attribute};
return if(!$a);
my $aNo = $a->{att_id};
$hash->{$aNo}{'att1'} = $a->{att1};
$hash->{$aNo}{'att2'} = $a->{att2};
$hash->{$aNo}{'att3'} = $a->{att3};
}
推荐阅读
- excel - 禁用excel VBA组合框/列表框中的一个选项?
- python - 与行号一致
- javascript - 带有轨道“行星”的 CSS 同心圆
- python - 给定一个长字符串,在字典中找到匹配的字符串
- python - 循环遍历 Selenium/Python 中标签内的标签
- r - 使用 Count 压缩行
- python - Docker 上的 Gunicorn 在 Mac 上出现错误
- c# - Logical error in display/math not displaying initial result
- python - 在python中设计类似结构的c的最佳方法
- google-sheets - 如何对同一单元格内的单元格值进行排名