2011/05/21

Perl JSON Formatter

#!/usr/bin/perl

use strict;
use warnings;
use Term::ReadLine;
use JSON;

my $term = new Term::ReadLine($ARGV[0], \*STDIN, \*STDOUT);
my @json_text;
while (defined(my $line = $term->readline())) {
 chomp $line;
 push @json_text, $line;
}
my $json_text = join('', @json_text);

print '=' x 80 . "\n";

my $json = JSON->new->pretty(1);
my $formatted_json_text = $json->encode($json->decode($json_text));

print $formatted_json_text;

p.s.
Remember to install Term::ReadLine::Gnu to make life easy.