I'm trying to create a simple JSON file. I wanted to try to get the names/keys output in a specific (non-alphanumeric) order (to make it easier on the human users of the JSON -- I know it's irrelevant to any automated parsers). Using the JSON module, I can get unsorted or alphanumerically sorted. Manually rolling it, I can get in whatever order I specify. Is there an option I'm not seeing in the JSON docs for altering the sort-order? or another module that has user-supplied sort order?
use warnings; use strict; use autodie; use JSON; use 5.010; my @order = qw/id disp ver auth/; my $dat = [ ({ id => 'a', disp => 'a', ver => 'a', auth => 'a' })x2 ]; + # dummy data local $\ = "\n"; print 'Unsorted => ', JSON->new->indent->space_after->encode( $dat ); print 'Alpha Sorted => ', JSON->new->indent->space_after->canonical->e +ncode( $dat ); print 'My Order => ', manual_ordered_json( $dat, \@order ); use Data::Dumper; sub manual_ordered_json{ my @list = @{$_[0]}; my @ordr = @{$_[1]}; my $out = "[\n"; for my $i ( 0 .. $#list ) { my $h = $list[$i]; $out .= " {\n"; for my $j ( 0 .. $#ordr ) { my $k = $ordr[$j]; next unless defined $k; next unless exists $h->{$k}; $out .= sprintf qq| "%s": "%s"|, $k, $h->{$k} // '< +undef>'; $out .= ',' if $j < $#ordr; $out .= "\n"; } $out .= " }"; $out .= "," if $i < $#list; $out .= "\n"; } $out .= "]\n"; return $out; }
(It's not overly important; this is mostly as a learning opportunity; my manual_ordered_json could have finished this one-off job for me already, but I was hoping to expand my toolbase knowledge.)
Thanks
In reply to Outputting JSON with sorted names/keys by pryrt
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |