Permalink
Browse files

Use JSON::Color when interactive

  • Loading branch information...
1 parent e3915ea commit 7548a5c36c9a918b9b388198d9912324707fe6ac Steven Haryanto (on PC) committed Nov 16, 2012
Showing with 47 additions and 18 deletions.
  1. +1 −0 dist.ini
  2. +27 −12 lib/Data/Format/Pretty/CompactJSON.pm
  3. +19 −6 lib/Data/Format/Pretty/JSON.pm
View
@@ -17,5 +17,6 @@ Test::More=0.96
[Prereqs]
perl=5.010000
JSON=0
+JSON::Color=0.04
;we must not depend on dfp, circular
@@ -4,23 +4,30 @@ use 5.010;
use strict;
use warnings;
-use Data::Format::Pretty::JSON;
-
require Exporter;
our @ISA = qw(Exporter);
our @EXPORT_OK = qw(format_pretty);
-my $json = JSON->new->utf8->allow_nonref;
-
# VERSION
sub content_type { "application/json" }
sub format_pretty {
- my ($data, $opts0) = @_;
- my %opts = $opts0 ? %$opts0 : ();
- $opts{pretty} = 0;
- Data::Format::Pretty::JSON::format_pretty($data, \%opts);
+ my ($data, $opts) = @_;
+ state $json;
+
+ $opts //= {};
+
+ if ($opts->{color} // (-t STDOUT)) {
+ require JSON::Color;
+ JSON::Color::encode_json($data, {pretty=>0, linum=>0});
+ } else {
+ if (!$json) {
+ require JSON;
+ $json = JSON->new->utf8->allow_nonref;
+ }
+ $json->encode($data);
+ }
}
1;
@@ -45,16 +52,24 @@ Some example output:
=head1 DESCRIPTION
-This module is a shortcut for using L<Data::Format::Pretty::JSON> with options
-C<pretty>=0.
+Like L<Data::Format::Pretty::JSON>, but will always print with JSON option C<<
+pretty => 0 >> (minimal indentation).
=head1 FUNCTIONS
=head2 format_pretty($data, \%opts)
-Return formatted data structure as JSON. See L<Data::Format::Pretty::JSON> for
-details.
+Return formatted data structure as JSON. Options:
+
+=over 4
+
+=item * color => BOOL
+
+Whether to enable coloring. The default is the enable only when running
+interactively.
+
+=back
=head1 SEE ALSO
@@ -4,23 +4,31 @@ use 5.010;
use strict;
use warnings;
-use JSON;
-
require Exporter;
our @ISA = qw(Exporter);
our @EXPORT_OK = qw(format_pretty);
-my $json = JSON->new->utf8->allow_nonref;
-
# VERSION
sub content_type { "application/json" }
sub format_pretty {
my ($data, $opts) = @_;
$opts //= {};
- $json->pretty($opts->{pretty} // 1);
- $json->encode($data);
+
+ state $json;
+
+ if ($opts->{color} // (-t STDOUT)) {
+ require JSON::Color;
+ JSON::Color::encode_json($data, {pretty=>1, linum=>1}) . "\n";
+ } else {
+ if (!$json) {
+ require JSON;
+ $json = JSON->new->utf8->allow_nonref;
+ }
+ $json->pretty($opts->{pretty} // 1);
+ $json->encode($data);
+ }
}
1;
@@ -65,6 +73,11 @@ Return formatted data structure as JSON. Options:
=over 4
+=item * color => BOOL
+
+Whether to enable coloring. The default is the enable only when running
+interactively. Currently also enable line numbering.
+
=item * pretty => BOOL (default 1)
Whether to pretty-print JSON.

0 comments on commit 7548a5c

Please sign in to comment.