blib/lib/App/JSONPretty.pm

filter: Statementstmt 66.6% 4 / 6 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 2 / 2 Podpod n/a totaltotal 75.0% 6 / 8 CC 1 SCAR 1.4
CC
1
Cov
67%
BEGIN
1.3
BEGIN
1.0
CRAP 1.1
↑ Summary
1 package App::JSONPretty;
2  
3 1 ▶use strictures 1;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 0 ▶use JSON ();
Subroutine BEGIN: called CC=1 SCAR=2.6
5 use Try::Tiny;
6  
7 our $VERSION = 1;
8  
9 my $usage = "Usage:
10 $0 <filename
11 $0 filename
12 ";
13  
14 sub new_json_object {
15 JSON->new->utf8->pretty->relaxed->canonical;
16 }
17  
18 sub source_filehandle {
19 if (@ARGV > 1) {
20 die "Too many arguments.\n${usage}";
21 } elsif (@ARGV == 1) {
22 open my $fh, '<', $ARGV[0]
23 or die "Couldn't open $ARGV[0]: $!";
24 $fh;
25 } else {
26 *STDIN;
27 }
28 }
29  
30 sub source_data {
31 my $src = source_filehandle;
32 do { local $/; <$src> }
33 or die "No source data supplied.\n${usage}";
34 }
35  
36 sub decode_using {
37 my ($json, $src_data) = @_;
38 try {
39 $json->decode($src_data)
40 } catch {
41 die "Error parsing JSON: $_\n";
42 }
43 }
44  
45 sub encode_using {
46 my ($json, $data_structure) = @_;
47 try {
48 $json->encode($data_structure)
49 } catch {
50 die "Error generating JSON: $_\n";
51 }
52 }
53  
54 sub run {
55 my $json = new_json_object;
56  
57 print STDOUT encode_using $json, decode_using $json, source_data;
58  
59 return 0;
60 }
61  
62 exit run unless caller;
63  
64 1;
65  
66 =head1 NAME
67  
68 jsonpretty - JSON prettification script
69  
70 =head1 SYNOPSIS
71  
72 $ jsonpretty <file.json
73 $ jsonpretty file.json
74  
75 =head1 DESCRIPTION
76  
77 The jsonpretty script reads the JSON file given on STDIN or as its first
78 argument, decodes it (allowing errors such as shell style comments and extra
79 trailing commas on lists), then pretty prints it.
80  
81 The pretty printed form is indented and has hash keys sorted and as such is
82 suitable for diffing.
83  
84 This program always works in utf8. If your JSON is not valid utf8, please ask
85 the nearest internationalisation expert to kill you with a big hammer.
86  
87 =head1 AUTHOR
88  
89 Matt S. Trout <mst@shadowcat.co.uk>
90  
91 =head1 CONTRIBUTORS
92  
93 None required yet. Maybe this code is perfect (hahahahaha ...).
94  
95 =head1 COPYRIGHT
96  
97 Copyright (c) 2011 the App::JSONPretty L</AUTHOR> and L</CONTRIBUTORS>
98 as listed above.
99  
100 =head1 LICENSE
101  
102 This library is free software and may be distributed under the same terms
103 as perl itself.
104  
105 =cut
↑ Summary