in reply to customized JSON pretty print

First use pretty and then remove superfluous whitespace:

use JSON; sub remove_newlines { my $str = shift; $str =~ s/^\s+//gsm; $str =~ s/\n//gsm; return $str; } %HoA = ('foo' => [1,2,3], 'bar' => ['a','b','c']); print "plain:\n".JSON->new->encode(\%HoA)."\n"; my $pretty = JSON->new->pretty->encode(\%HoA); $pretty =~ s/(\[.*?\])/remove_newlines($1)/egsm; print "pretty:\n$pretty";

This will not work with nested brackets or brackets within strings, though.

Replies are listed 'Best First'.
Re^2: customized JSON pretty print
by Anonymous Monk on Feb 16, 2015 at 13:37 UTC
    Thank you for the quick reply, this is indeed a good solution for my example and a nice use of multi-line regexes. However for more complex JSON (the type one would usually want pretty printing for) this will not work, as you have noted. Any suggestions for that case?

    A related issue in pretty printing (sorry if this goes against the customs of the Monastery) is the ordering of keys. The JSON module allows to use the order provided by the Perl hash (which typically changes between executions) or to sort the keys alphabetically. However, I would like to use a custom sort order to improve readability of the output. Any thoughts?

      A quick look into JSON::PP reveals that there is a function array_to_json and in there a line

      my ($pre, $post) = $indent ? $self->_up_indent() : ('', '');

      If you change that to

      my ($pre, $post) = ('', '');

      pretty stops prettifying arrays.

      use JSON::PP; my %HoA = ('foo' => [1,2,3], 'bar' => ['a','b','c']); print "plain:\n".JSON::PP->new->encode(\%HoA)."\n"; print "pretty:\n".JSON::PP->new->pretty->encode(\%HoA);

      Custom sort or ASCIIbetical sort? ->canonical(1) on the json object will sort the keys in a stable manner.

      --MidLifeXis