2015-01-08 48 views
0

我想将json文件转换为xml。因此,扫描JSON目录,并且如果到达那里的任何文件将被转换为xml并移动到xml目录。Perl中格式不正确的JSON字符串

但是我正在此错误

的ReadLine()上闭合的文件句柄$跳频在json.pl管线29
格式错误JSON字符串,既不阵列,对象,数字,字符串或原子,在字符(前 “(字符串的结束)”)在json.pl线34

json.pl

#!/usr/bin/perl 

use strict; 
use warnings; 
use File::Copy; 

binmode STDOUT, ":utf8"; 
use utf8; 

use JSON; 
use XML::Simple; 

# Define input and output directories 
my $indir = 'json'; 
my $outdir = 'xml'; 

# Read input directory 
opendir DIR, $indir or die "Failed to open $indir"; 
my @files = readdir(DIR); 
closedir DIR; 

# Read input file in json format 
for my $file (@files) 
{ 
my $json; 
{ 
    local $/; #Enable 'slurp' mode 
    open my $fh, "<", "$indir/$file"; 
    $json = <$fh>; 
    close $fh; 
} 

# Convert JSON format to perl structures 
my $data = decode_json($json); 

# Output as XML 
open OUTPUT, '>', "$outdir/$file" or die "Can't create filehandle: $!"; 
select OUTPUT; $| = 1; 
print "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"; 
print XMLout($data); 
print "\n" ; 
close(OUTPUT); 
unlink "$indir/$file"; 

} 

example.js偏移0在

{ 
"Manager": 
    { 
     "Name" : "Mike", 
     "Age": 28, 
     "Hobbies": ["Music"] 
    }, 
"employees": 
    [ 
     { 
      "Name" : "Helen", 
      "Age": 26, 
      "Hobbies": ["Movies", "Tennis"] 
      }, 
     { 
      "Name" : "Rich", 
      "Age": 31, 
      "Hobbies": ["Football"] 

     } 
    ] 
} 

回答

4

你是不是在open检查错误,你是不是跳过目录条目(readdir将返回...条目)。

如果使用

open my $fh, "<", "$indir/$file" or die "$file: $!"; 

你可能会很快发现问题。

“readline()on closed filehandle $ fh”在说“open $fh失败,但你仍然继续前进”。

0

正如@cjm指出的那样,问题在于您试图打开并读取源目录中的目录以及文件。

这是一个解决方案,它也使用autodie来避免不断检查所有IO操作的状态。我也收拾了一些东西。

#!/usr/bin/perl 

use utf8; 
use strict; 
use warnings; 
use autodie; 

use open qw/ :std :encoding(utf8) /; 

use JSON qw/ decode_json /; 
use XML::Simple qw/ XMLout /; 

my ($indir, $outdir) = qw/ json xml /; 

my @indir = do { 
    opendir my $dh, $indir; 
    readdir $dh; 
}; 

for my $file (@indir) { 

    my $infile = "$indir/$file"; 
    next unless -f $infile; 

    my $json = do { 
    open my $fh, '<', $infile; 
    local $/; 
    <$fh>; 
    }; 

    my $data = decode_json($json); 

    my $outfile = "$outdir/$file"; 
    open my $out_fh, '>', "$outdir/$file"; 
    print $out_fh '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>', "\n"; 
    print $out_fh XMLout($data), "\n"; 
    close $out_fh; 

    unlink $infile; 
} 
+0

为了处理故障,在'decode_json'周围放置一个'eval'会很好吗? 'decode_json'发现错误。 –