Skip to content

Instantly share code, notes, and snippets.

@moznion
Last active July 19, 2018 02:05
Show Gist options
  • Save moznion/4608205 to your computer and use it in GitHub Desktop.
Save moznion/4608205 to your computer and use it in GitHub Desktop.
Convert JSON file to XML file.
#!/usr/bin/env perl
use strict;
use warnings;
use utf8;
use 5.012000;
use autodie;
use XML::XML2JSON;
sub get_json_contents {
my ($json_filename) = @_;
open my $fh, '<', $json_filename or die $!;
my @json = split /\n/, do { local $/; <$fh> };
close $fh;
return join '', @json;
}
sub convert2xml {
my ($json) = @_;
local $SIG{__WARN__} = sub {
# Do nothing.
}; # Suppress warning of XML::XML2JSON->new()
my $xml2json = XML::XML2JSON->new(
module => 'JSON::XS',
pretty => 1,
);
return $xml2json->json2xml($json);
}
sub decide_xml_filename {
my ($json_filename) = @_;
my @xml_filename = split /\./, $json_filename;
$xml_filename[-1] = 'xml';
return join '.', @xml_filename;
}
sub write_xml_file {
my ( $xml_filename, $xml ) = @_;
open my $fw, '>', $xml_filename or die $!;
print $fw $xml;
close $fw;
}
my $json_filename = $ARGV[0];
my $xml_contents = convert2xml( get_json_contents($json_filename) );
write_xml_file( decide_xml_filename($json_filename), $xml_contents );
@OndraZizka
Copy link

Hi, how do you use it? Is it ready to consume one JSON object {...} per line? Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment