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 | |
8add3309 |
10 | our $VERSION = '0.000001'; |
11 | $VERSION = eval $VERSION; |
dd1bf371 |
12 | |
8add3309 |
13 | my $real = JSON->new->relaxed->allow_nonref->utf8; |
14 | |
15 | our @EXPORT_OK = qw( encode_json decode_json ); |
dd1bf371 |
16 | |
17 | sub encode_json { |
18 | my $data = shift; |
19 | return _encode($data, 0); |
20 | } |
21 | |
8add3309 |
22 | sub decode_json { |
23 | my $str = shift; |
24 | return $real->decode($str); |
25 | } |
26 | |
dd1bf371 |
27 | sub _indent { |
28 | my $str = shift; |
29 | $str =~ s{^}{ }gm; |
30 | return $str; |
31 | } |
32 | |
33 | sub _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 | |
58 | 1; |
8add3309 |
59 | |
60 | __END__ |
61 | |
62 | =head1 NAME |
63 | |
64 | JSON::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 | |
75 | This module allows to create a JSON variant that is suitable for easy |
76 | diffing. 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 | |
88 | The data can be read again by a relaxed L<JSON> parser or the exported |
89 | L</decode_json> function. |
90 | |
91 | =head1 EXPORTS |
92 | |
93 | =head2 encode_json |
94 | |
95 | my $json = encode_json($data); |
96 | |
97 | Turns a Perl data structure into relaxed JSON. |
98 | |
99 | =head2 decode_json |
100 | |
101 | my $data = decode_json($json); |
102 | |
103 | Turns relaxed JSON into a Perl data structure. |
104 | |
38147579 |
105 | =head1 SPONSORED |
106 | |
107 | The development of this module was sponsored by L<http://socialflow.com/>. |
108 | |
8add3309 |
109 | =cut |