Perl中的JSON编码损坏(missign逗号)

时间:2017-01-30 12:12:22

标签: json perl

我的自定义代码(在Perl上)给出了下一个错误的JSON,块之间缺少逗号:

{
    "data": [{
        "{#LOGFILEPATH}": "/tmp/QRZ2007.tcserverlogs",
        "{#LOGFILE}": "QRZ2007"
    } **missing comma** {
        "{#LOGFILE}": "ARZ2007",
        "{#LOGFILEPATH}": "/tmp/ARZ2007.tcserverlogs"
    }]
}

我可怕的代码:

#!/usr/bin/perl

    use strict;
    use warnings;
    use File::Basename;
    use utf8;
    use JSON;
    binmode STDOUT, ":utf8";


    my $dir = $ARGV[0];    
    my $json = JSON->new->utf8->space_after;
    opendir(DIR, $dir) or die $!;
    print '{"data": [';
    while (my $file = readdir(DIR)) {

        next unless (-f "$dir/$file");

        next unless ($file =~ m/\.tcserverlogs$/);
        my $fullPath = "$dir/$file";
        my $filenameshort = basename($file,  ".tcserverlogs");

        my $data_to_json = {"{#LOGFILEPATH}"=>$fullPath,"{#LOGFILE}"=>$filenameshort};
        my $data_to_json = {"{#LOGFILEPATH}"=>$fullPath,"{#LOGFILE}"=>$filenameshort};
        print $json->encode($data_to_json);

    }

    print ']}'."\n";
    closedir(DIR);
    exit 0;

亲爱的团队我不是程序员,请知道如何修复它,谢谢!

1 个答案:

答案 0 :(得分:4)

如果您不打印逗号,则不会使用逗号。

您正在尝试从预编码的较小数据结构中构建自己的JSON字符串。除非你告诉Perl何时使用逗号,否则这将无效。你可以做到这一点,但是将所有数据收集到一个Perl数据结构中会更容易,这个数据结构等同于你想要生成的JSON字符串,并且当你完成时,可以一次性编码整个事物。

my $dir  = $ARGV[0];
my $json = JSON->new->utf8->space_after;
my @data;

opendir( DIR, $dir ) or die $!;
while ( my $file = readdir(DIR) ) {

    next unless ( -f "$dir/$file" );
    next unless ( $file =~ m/\.tcserverlogs$/ );
    my $fullPath = "$dir/$file";
    my $filenameshort = basename( $file, ".tcserverlogs" );

    my $data_to_json = { "{#LOGFILEPATH}" => $fullPath, "{#LOGFILE}" => $filenameshort };
    push @data, $data_to_json;
}
closedir(DIR);

print $json->encode( { data => \@data } );