From: Robert 'phaylon' Sedlacek Date: Wed, 30 May 2012 20:56:47 +0000 (+0000) Subject: Initial implementation X-Git-Tag: v0.000001~12 X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=commitdiff_plain;h=dd1bf37158da1c569f745f980a5b970aaf455b69;p=scpubgit%2FJSON-Diffable.git Initial implementation --- dd1bf37158da1c569f745f980a5b970aaf455b69 diff --git a/lib/JSON/Diffable.pm b/lib/JSON/Diffable.pm new file mode 100644 index 0000000..7530d9c --- /dev/null +++ b/lib/JSON/Diffable.pm @@ -0,0 +1,48 @@ +use strictures 1; + +package JSON::Diffable; + +use JSON (); +use Exporter 'import'; + +my $real = JSON->new->allow_nonref->utf8; + +our @EXPORT_OK = qw( encode_json ); + +sub encode_json { + my $data = shift; + return _encode($data, 0); +} + +sub _indent { + my $str = shift; + $str =~ s{^}{ }gm; + return $str; +} + +sub _encode { + my $data = shift; + if (ref $data eq 'HASH') { + return sprintf "{\n%s}", + join '', + map { + my $key = $real->encode($_); + my $data = _encode($data->{$_}); + _indent("$key: $data") . ",\n"; + } + sort keys %$data; + } + elsif (ref $data eq 'ARRAY') { + return sprintf "[\n%s]", + join '', + map { + _indent(_encode($_)) . ",\n"; + } + @$data; + } + else { + return $real->encode($data); + } +} + +1;