[sf-perl] JSON sorting question

David Alban extasia at extasia.org
Mon Nov 22 11:31:25 PST 2010


On Mon, Nov 22, 2010 at 11:12 AM, Francisco Obispo <fobispo at isc.org> wrote:
> You shouldn't use $a or $b directly since they are not defined for the method sort_by.
>
> try from 'perldoc JSON':
>
> $json->sort_by(sub { lc $JSON::PP::a cmp lc $JSON::PP::b });

thanks francisco.

now i have:

#!/usr/bin/perl

use strict;
use warnings;

use lib '/nas/reg/lib/perl';

use JSON;

my $stuff = {
  foo => {
    baz => {
      items => [
        'Z',
        'y',
        'X',
        'w',
      ],
    },
    BAR => {
      items => [
        'c',
        'a',
        'D',
        'B',
      ],
    },
  },
};

my $json = new JSON;

$json->canonical( 1 );
$json->sort_by(sub { lc $JSON::PP::a cmp lc $JSON::PP::b });

my $json_text = $json->pretty->encode( $stuff );

print "$json_text\n";


which outputs:

{
   "foo" : {
      "BAR" : {
         "items" : [
            "c",
            "a",
            "D",
            "B"
         ]
      },
      "baz" : {
         "items" : [
            "Z",
            "y",
            "X",
            "w"
         ]
      }
   }
}

it seems to be sorting only the highest level keys.  any idea on how
to make it sort at every level?

is this the case where i'd have to write my own sort routine that
sorted arbitrary data structures too arbitrary levels?

thanks.
-- 
Live in a world of your own, but always welcome visitors.


More information about the SanFrancisco-pm mailing list