Commit | Line | Data |
dd1bf371 |
1 | use strictures 1; |
2 | |
3 | package JSON::Diffable; |
4 | |
5 | use JSON (); |
6 | use Exporter 'import'; |
7 | |
8add3309 |
8 | our $VERSION = '0.000001'; |
9 | $VERSION = eval $VERSION; |
dd1bf371 |
10 | |
8add3309 |
11 | my $real = JSON->new->relaxed->allow_nonref->utf8; |
12 | |
13 | our @EXPORT_OK = qw( encode_json decode_json ); |
dd1bf371 |
14 | |
15 | sub encode_json { |
16 | my $data = shift; |
17 | return _encode($data, 0); |
18 | } |
19 | |
8add3309 |
20 | sub decode_json { |
21 | my $str = shift; |
22 | return $real->decode($str); |
23 | } |
24 | |
dd1bf371 |
25 | sub _indent { |
26 | my $str = shift; |
27 | $str =~ s{^}{ }gm; |
28 | return $str; |
29 | } |
30 | |
31 | sub _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 | |
56 | 1; |
8add3309 |
57 | |
58 | __END__ |
59 | |
60 | =head1 NAME |
61 | |
62 | JSON::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 | |
73 | This module allows to create a JSON variant that is suitable for easy |
74 | diffing. 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 | |
86 | The data can be read again by a relaxed L<JSON> parser or the exported |
87 | L</decode_json> function. |
88 | |
89 | =head1 EXPORTS |
90 | |
91 | =head2 encode_json |
92 | |
93 | my $json = encode_json($data); |
94 | |
95 | Turns a Perl data structure into relaxed JSON. |
96 | |
97 | =head2 decode_json |
98 | |
99 | my $data = decode_json($json); |
100 | |
101 | Turns relaxed JSON into a Perl data structure. |
102 | |
103 | =cut |