[sf-perl] JSON sorting question

David Alban extasia at extasia.org
Mon Nov 22 11:04:15 PST 2010


greetings,

given the program:

#!/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 = $json->canonical( 1 );
$json = $json->sort_by( sub { return lc( $a ) cmp lc( $b ) } );

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

print "$json_text\n";

output is:

Name "main::b" used only once: possible typo at junk.perl line 34.
Name "main::a" used only once: possible typo at junk.perl line 34.
{
   "foo" : {
      "baz" : {
         "items" : [
            "Z",
            "y",
            "X",
            "w"
         ]
      },
      "BAR" : {
         "items" : [
            "c",
            "a",
            "D",
            "B"
         ]
      }
   }
}

1. not sure how to get around the complaints about $a and $b.  this is
a sort routine, yes?

2. the result (of my real program, not this test program) will be a
human editable file.  i want all items in lexigraphical order.  that
is, i'd like the output to be ordered like:

  BAR
    a
    B
    c
    D
  baz
    w
    X
    y
    Z

there will be a lot of data, and it would greatly reduce the effort of
a person trying to determine if particular data exists in the file if
the items are all sorted.  but i don't know how to accomplish this.

if i comment out the "$json = $json->sort_by( ... )" line, i get a
little closer.  it sorts 'BAR' in front of 'baz' correctly, but
doesn't modify the order of the "items":

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

what am i missing?

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


More information about the SanFrancisco-pm mailing list