首页 > 解决方案 > 在 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

标签: jsonperl

解决方案


一种可能是检查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};
}

推荐阅读