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