Home > Software engineering >  Can we set the $JSON::PP::canonical to sort keys in the output encoded data?
Can we set the $JSON::PP::canonical to sort keys in the output encoded data?

Time:07-31

use JSON::PP qw(encode_json);

my $json = JSON::PP->new->canonical->allow_nonref;
my $encoded = $json->encode($somehash);

# I would like to use the one-liner code below.
my $json = encode_json($somehash);

# Can I set properties like these? Which one is correct?
$JSON::PP::P_CANONICAL = 1;
$JSON::PP::P_ALLOW_NONREF = 1;
# or
$JSON::PP::canonical = 1;
$JSON::PP::allow_nonref = 1;

I want to use the simple encode_json() function. Can we set the canonical and allow_nonref properties? Which one is correct?

CodePudding user response:

No. But nothing stops you from creating your own sub.

sub my_encode_json {
   return JSON::PP->new->canonical->allow_nonref->encode( $_[0] );
}

or

sub my_encode_json {
   state $encoder = JSON::PP->new->canonical->allow_nonref;
   return $encoder->encode( $_[0] );
}
  • Related