Algorithm-Diff-JSON

 view release on metacpan or  search on metacpan

lib/Algorithm/Diff/JSON.pm  view on Meta::CPAN

package Algorithm::Diff::JSON;

use strict;
use warnings;

use Algorithm::Diff qw(diff);
use Cpanel::JSON::XS qw(encode_json);

use Sub::Exporter -setup  => { exports => [ 'json_diff' ] };

our $VERSION = '1.000';

sub json_diff {
    my @changes = ();

    foreach my $diff (map { @{$_} } diff(@_)) {
        my($action, $this_line, $content) = @{$diff};
        if(defined($changes[$this_line])) {
            $changes[$this_line] = {
                change => {
                    add    => $content,
                    remove => $changes[$this_line]->{remove}
                }
            };
        } elsif($action eq '+') {
            $changes[$this_line] = { add  => $content };
        } elsif($action eq '-') {
            $changes[$this_line] = { remove => $content };
        }
    }
    return encode_json([
        map { defined($changes[$_]) ? { element => $_, %{$changes[$_]} } : () }
        0 .. $#changes
    ]);
}

=head1 NAME

Algorithm::Diff::JSON - find the differences between two lists and report on them in JSON

=head1 SYNOPSIS

This perl code:

    use Algorithm::Diff::JSON qw(json_diff);

    my $json = json_diff(
        [0,      1, 2, 3, 4, 5,      6],
        ['zero', 1, 2, 3,    5, 5.5, 6]
    );

will generate this JSON:

    [
        { "element": 0, "change": { "remove": 0, "add": "zero" } },
        { "element": 4, "remove": 4 },
        { "element": 5, "add": 5.5 }
    ]

(well, an ugly, minimised, equivalent version of that JSON anyway)

=head1 FUNCTIONS

There is only one function, which is a simple wrapper around L<Algorithm::Diff>'s
C<diff> function:

=head2 json_diff



( run in 1.017 second using v1.01-cache-2.11-cpan-39bf76dae61 )