perl从文件和循环加载json

时间:2017-06-05 03:03:58

标签: json perl

我有一个这样的文件:

{
    "dev":
    {
        "data": "1"
    },
    "stg":
    {
        "data": "1"
    },
    "pre":
    {
        "data": "1"
    },
    "prod":
    {
        "data": "1"
    },
}

我像这样加载json:

open(FH,"<",$file) or die "environments.json file doesn't exists!\n";
my $data = <FH>;

my $ret = JSON::decode_json( $data );

正确加载,我可以这样做:

print "Dumper: " .  Dumper($ret) . "\n";

但是当我尝试使用:

进行循环时
foreach my $env( @$ret )
{
    print "Environment: " . $env->{"data"} . "\n";
}

我明白了:

Not an ARRAY reference at ./launcher.pl line 20, <FH> line 1.

foreach my $env( @$ret )行 感谢帮助!

谢谢!

大卫

1 个答案:

答案 0 :(得分:2)

JSON中没有数组。

for my $env_name (keys(%$ret)) {
   my $env = $ret->{$env_name};

   ... $env->{data} ...

}