キーの順序を強制するために、ある種の結び付けられたハッシュを使用する必要があります:Tie::IxHash。
次は、コンセプトの証明です:
#!/usr/bin/env perl
use strict;
use warnings;
use v5.10;
use JSON::XS;
my $JSON = JSON::XS->new->utf8->indent->space_after->convert_blessed;
my $data = {
a => 1,
b => 2,
c => 3,
d => 4,
e => 5,
};
say $JSON->encode($data); # Keys are unordered
bless $data, 'MyAlphaHash';
say $JSON->encode($data); # Keys are alphabetized
package MyAlphaHash;
use Tie::IxHash;
sub TO_JSON {
my $self = shift;
tie my %hash, 'Tie::IxHash', %$self;
tied(%hash)->Reorder(sort keys %hash);
return \%hash;
}
出力:
$ perl ordered.pl
{
"e": 5,
"c": 3,
"a": 1,
"b": 2,
"d": 4
}
{
"a": 1,
"b": 2,
"c": 3,
"d": 4,
"e": 5
}
あなたはJSONオブジェクトを読み、修正するために使用されているいくつかのコードを共有することができます –