I am trying to convert json file to xml. So JSON directory is scanned and if any file that arrives there will be converted to xml and moved to xml directory.
But I am getting this error
readline() on closed filehandle $fh at json.pl line 29.
Malformed JSON string, neither array, object, number, string or atom, at character offset 0 (before "(end of string)") at json.pl line 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.json
{
"Manager":
{
"Name" : "Mike",
"Age": 28,
"Hobbies": ["Music"]
},
"employees":
[
{
"Name" : "Helen",
"Age": 26,
"Hobbies": ["Movies", "Tennis"]
},
{
"Name" : "Rich",
"Age": 31,
"Hobbies": ["Football"]
}
]
}