Based on this post, I am trying to understand how sort_by
works in JSON::PP
.
When I run this code
#!/usr/bin/perl
use strict;
use warnings;
use JSON::PP;
use Data::Dumper qw(Dumper);
my $h = {
22 => { title => "c", name => "d" },
1 => { title => "1", name => "a" },
10 => { title => "a", name => "c" },
5 => { title => "b", name => "b" },
};
my $sorter = sub {
# See what's going on.
print "$JSON::PP::a cmp $JSON::PP::b\n";
print Dumper(\@_, $_);
<STDIN>; # press return to continue
$JSON::PP::a cmp $JSON::PP::b
};
my $js = JSON::PP->new;
my $output = $js->sort_by($sorter)->encode($h);
print $output . "\n";
it first sorts the inner keys, and then the outer keys, which determines the final order in the JSON string.
Right now it outputs
{"1":{"name":"a","title":"1"},"10":{"name":"c","title":"a"},"22":{"name":"d","title":"c"},"5":{"name":"b","title":"b"}}
and what I would like to end up with is that it is sorted by title
ie.
{"1":{"name":"a","title":"1"},"5":{"name":"b","title":"b"}"10",{"name":"c","title":"a"},"22":{"name":"d","title":"c"}}
I suppose the first problem is to disable the last outter key sort?
Then how do I get hold of the value of title
? When the algorithm runs, $JSON::PP::a
and $JSON::PP::b
contains the value name
and title
from the same hash.
This I can't figure out. Can anyone explain this, and/or help me write this algorithm?