moytrage

json_pretty_print.pl

Feb 29th, 2012
239
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 0.74 KB | None | 0 0
  1. # Pretty print input JSON-formatted single lines into pretty huge array of JSON objects.
  2.  
  3. use strict;
  4. use warnings;
  5. use JSON;
  6.  
  7. our $json_output_config = { pretty => 1, utf8 => 0, ascii => 1, canonical => 1 };
  8.  
  9. #use IO::Handle qw();
  10.  
  11. die "Usage: script input.lines.json output.pretty.json" unless scalar @ARGV == 2;
  12.  
  13. open my $f, "<$ARGV[0]" or die "Can't open input for read.";
  14. binmode $f;
  15.  
  16. my @all;
  17.  
  18. my $line = 0;
  19.  
  20. while (<$f>) {
  21.     next if /^\s*$/;
  22.  
  23.     printf STDERR ".";
  24.  
  25.     push @all, from_json($_);
  26.  
  27.     ++$line;
  28. }
  29.  
  30. close $f;
  31.  
  32. open my $g, ">:encoding(utf-8)","$ARGV[1]" or die "Can't open output for write.";
  33. print $g chr(0xFEFF) if $json_output_config->{utf8}; # BOM
  34.  
  35. print $g to_json(\@all, $json_output_config);
  36.  
  37. close $g;
Advertisement
Add Comment
Please, Sign In to add comment