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;
