perl: how to sort a JSON structure on something other than “root” key attributes

后端 未结 1 1825
终归单人心
终归单人心 2020-12-28 23:50

Perl: How can I sort a complex structure using JSON::PP ?

From the JSON Documentation:

As the sorting routine runs in the JSON::PP scope, t

相关标签:
1条回答
  • 2020-12-29 00:38

    I'm not certain I understand how you want the JSON output to be sorted -- aside from sorting by hash key. If that's all you want, just pass the canonical method a true argument.

    use strict;
    use warnings;
    
    use JSON::PP;
    
    # A simple hash-of-hashes for exploration.
    my $h = {
        Z => { c => 1, d => 2 },
        A => { a => 3, r => 4 },
        B => { c => 5, x => 6 },
        S => { q => 7, d => 8 },
    };
    
    my $js = JSON::PP->new;
    $js->canonical(1);
    
    my $output = $js->encode($h);
    print $output;
    

    If you do use the sort_by method, it does not make sense to use $_ within the sort block: what would it represent? It was not clear from the documentation what arguments the sort_by code will receive. Using Data::Dumper like this:

    use Data::Dumper qw(Dumper);
    
    my $sorter = sub {
        # See what's going on.
        print "$JSON::PP::a cmp $JSON::PP::b\n";
        print Dumper(\@_, $_);
        <STDIN>;
    
        # Sort hash keys alphabetically.
        $JSON::PP::a cmp $JSON::PP::b;
    };
    
    my $output = $js->sort_by($sorter)->encode($h);
    

    You can infer that sort_by works like this: (1) it receives two arguments, the JSON::PP object and the hash ref currently being worked with; and (2) the $JSON::PP::a and $JSON::PP::b variables hold the hash keys being compared. But note that the hash ref refers to the JSON output as it is being built from the leaf nodes upward. It does not refer to your original data structure. This would seem to make the task of writing a comparator a bit trickier. Good luck.

    my $sorter = sub {
        my ($json_pp_object, $hash_ref) = @_;
    
        # Write your own comparator here.
    };
    
    my $output = $js->sort_by($sorter)->encode($h);
    
    0 讨论(0)
提交回复
热议问题