Initial implementation
Robert 'phaylon' Sedlacek [Wed, 30 May 2012 20:56:47 +0000 (20:56 +0000)]
lib/JSON/Diffable.pm [new file with mode: 0644]

diff --git a/lib/JSON/Diffable.pm b/lib/JSON/Diffable.pm
new file mode 100644 (file)
index 0000000..7530d9c
--- /dev/null
@@ -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;