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