2015-01-08 12 views
0

json 파일을 xml로 변환하려고합니다. 그래서 JSON 디렉토리가 스캔되어 도착한 파일이 xml로 변환되어 xml 디렉토리로 옮겨집니다.변형 된 JSON 문자열 (Perl)

하지만 json.pl 줄에서이 오류를 폐쇄 핸들의 $의 FH에

의 readline()을 얻고 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으로 지적했듯이 문제는 사용자가 원본 디렉토리의 파일과 디렉토리를 열어 읽으려고한다는 것입니다.

이 문제를 해결하고 모든 IO 작업의 상태를 지속적으로 확인하지 않으려면 autodie도 사용하십시오. 나는 또한 물건을 조금 정돈했다.

#!/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' 오류가 발생합니다. –