'Perl: JSON::XS Is it possible to force boolean decoding as 1/0?

Package JSON::XS uses JSON::XS::Boolean objects to represent true/false. Is it possible to force decoding true/false json values as 1/0 Perl numbers?

#!/usr/bin/env perl

use JSON::XS;
use Data::Dumper;

my $json = decode_json(join('', <DATA>));
print Dumper $json;

__DATA__
{
    "test_true": true,
    "test_false": false
}

Output:

$VAR1 = {
          'test_true' => bless( do{\(my $o = 1)}, 'JSON::XS::Boolean' ),
          'test_false' => bless( do{\(my $o = 0)}, 'JSON::XS::Boolean' )
        };

I want something like this after decode_json:

$VAR1 = {
          'test_true' => 1,
          'test_false' => 0
        };

Reason: In some cases, it's hard to predict how JSON::XS::Boolean will be serialized with, for example, SOAP serializer or another one.

PerlMonks discussion.



Solution 1:[1]

No. The values are blessed objects. They can only have the values allowed in JSON::XS::Boolean.

Solution 2:[2]

With Cpanel::JSON::XS, the unblessed_bool option controls this. So, you could use the following:

use Cpanel::JSON::XS qw( );

my $j = Cpanel::JSON::XS->new->utf8->unblessed_bool;

my $data = $j->decode( $json );

JSON::XS doesn't (currently) have an equivalent option. You would have to traverse the data returned structure and fix it up.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 shawnhcorey
Solution 2