Skip to content

Instantly share code, notes, and snippets.

@Geczy
Created November 18, 2015 20:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Geczy/36cc1379bbc7b4fce044 to your computer and use it in GitHub Desktop.
Save Geczy/36cc1379bbc7b4fce044 to your computer and use it in GitHub Desktop.
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