我正在尝试将 json 文件转换为 xml。所以 JSON 目录被扫描,如果有任何文件到达那里将被转换为 xml 并移动到 xml 目录。
但我收到了这个错误
readline() 在 json.pl 第 29 行的已关闭文件句柄 $fh 上。
格式错误的 JSON 字符串,既不是数组、对象、数字、字符串也不是原子,在 json.pl 第 34 行的字符偏移量 0(“(字符串结尾)”之前)
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";
}
例子.json
{
"Manager":
{
"Name" : "Mike",
"Age": 28,
"Hobbies": ["Music"]
},
"employees":
[
{
"Name" : "Helen",
"Age": 26,
"Hobbies": ["Movies", "Tennis"]
},
{
"Name" : "Rich",
"Age": 31,
"Hobbies": ["Football"]
}
]
}