Created
November 18, 2015 20:09
-
-
Save Geczy/36cc1379bbc7b4fce044 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use strict; | |
use warnings; | |
use JSON; | |
## @ARG is a special Perl array that contains the script's command line arguments | |
my $input = $ARGV[0]; | |
## Our input lines contain two columns, so we should define the variables that correspond to each column | |
my ($key, $value); | |
## Open the file, plus some sensible error checking | |
open(DATAFILE, "$input") || die("Can't open $input:!\n"); | |
## Loop through the file one line at a time | |
my @objects; | |
my %hash = (); | |
while (<DATAFILE>) { | |
## $_ is a special Perl variable containing the current line (in this case) | |
chomp; | |
if( /^$/ ) { | |
if( keys(%hash) ) | |
{ | |
push(@objects, \%hash); | |
# print("Pushed.\n"); | |
%hash = (); | |
} | |
} | |
else | |
{ | |
## Use split() to get the fields. "\t" is the tab character. | |
($key, $value) = split(":", $_); | |
$key =~ s/"/\\"/g; | |
$value =~ s/"/\\"/g; | |
$value =~ s/^\s*//; | |
$value =~ s/\s*$//; | |
$hash{$key} = $value; | |
} | |
} | |
if( keys(%hash) ) | |
{ | |
# print("Pushed (eof.)\n"); | |
push(@objects, \%hash); | |
} | |
my $json_str = encode_json(\@objects); # This will work now | |
print "$json_str"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment