decoder and docs
[scpubgit/JSON-Diffable.git] / lib / JSON / Diffable.pm
CommitLineData
dd1bf371 1use strictures 1;
2
3package JSON::Diffable;
4
5use JSON ();
6use Exporter 'import';
7
8add3309 8our $VERSION = '0.000001';
9$VERSION = eval $VERSION;
dd1bf371 10
8add3309 11my $real = JSON->new->relaxed->allow_nonref->utf8;
12
13our @EXPORT_OK = qw( encode_json decode_json );
dd1bf371 14
15sub encode_json {
16 my $data = shift;
17 return _encode($data, 0);
18}
19
8add3309 20sub decode_json {
21 my $str = shift;
22 return $real->decode($str);
23}
24
dd1bf371 25sub _indent {
26 my $str = shift;
27 $str =~ s{^}{ }gm;
28 return $str;
29}
30
31sub _encode {
32 my $data = shift;
33 if (ref $data eq 'HASH') {
34 return sprintf "{\n%s}",
35 join '',
36 map {
37 my $key = $real->encode($_);
38 my $data = _encode($data->{$_});
39 _indent("$key: $data") . ",\n";
40 }
41 sort keys %$data;
42 }
43 elsif (ref $data eq 'ARRAY') {
44 return sprintf "[\n%s]",
45 join '',
46 map {
47 _indent(_encode($_)) . ",\n";
48 }
49 @$data;
50 }
51 else {
52 return $real->encode($data);
53 }
54}
55
561;
8add3309 57
58__END__
59
60=head1 NAME
61
62JSON::Diffable - A relaxed and easy diffable JSON variant
63
64=head1 SYNOPSIS
65
66 use JSON::Diffable qw( encode_json decode_json );
67
68 $json = encode_json $data;
69 $data = decode_json $json;
70
71=head1 DESCRIPTION
72
73This module allows to create a JSON variant that is suitable for easy
74diffing. This means:
75
76=over
77
78=item * Commas after each hash or array element.
79
80=item * Consistent indentation
81
82=item * One line per entry
83
84=back
85
86The data can be read again by a relaxed L<JSON> parser or the exported
87L</decode_json> function.
88
89=head1 EXPORTS
90
91=head2 encode_json
92
93 my $json = encode_json($data);
94
95Turns a Perl data structure into relaxed JSON.
96
97=head2 decode_json
98
99 my $data = decode_json($json);
100
101Turns relaxed JSON into a Perl data structure.
102
103=cut