Skip to content

Commit

Permalink
Merge pull request #2192 from haarg/json-encode-core-bools
Browse files Browse the repository at this point in the history
Mojo::JSON: encode core boolean values as json bools
  • Loading branch information
kraih authored Aug 13, 2024
2 parents dde462b + 2a5e627 commit 6330775
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
9 changes: 9 additions & 0 deletions lib/Mojo/JSON.pm
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ use constant JSON_XS => $ENV{MOJO_NO_JSON_XS}
? 0
: !!eval { require Cpanel::JSON::XS; Cpanel::JSON::XS->VERSION('4.09'); 1 };

use constant CORE_BOOLS => defined &builtin::is_bool;

BEGIN {
warnings->unimport('experimental::builtin') if CORE_BOOLS;
}

our @EXPORT_OK = qw(decode_json encode_json false from_json j to_json true);

# Escaped special character map
Expand Down Expand Up @@ -250,6 +256,9 @@ sub _encode_value {
# Null
return 'null' unless defined $value;

# Boolean
return $value ? 'true' : 'false' if CORE_BOOLS && builtin::is_bool($value);

# Number
no warnings 'numeric';
return $value
Expand Down
8 changes: 8 additions & 0 deletions t/mojo/json.t
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,14 @@ subtest 'Encode number' => sub {
is $bytes, '23.3', 'encode 23.3';
};

subtest 'Encode boolean' => sub {
plan skip_all => 'No core boolean support' if !defined &builtin::is_bool;
my $bytes = encode_json [!!1];
is $bytes, '[true]', 'encode [!!1]';
$bytes = encode_json [!!0];
is $bytes, '[false]', 'encode [!!0]';
};

subtest 'Faihu roundtrip' => sub {
my $bytes = j(["\x{10346}"]);
is b($bytes)->decode('UTF-8'), "[\"\x{10346}\"]", 'encode ["\x{10346}"]';
Expand Down

0 comments on commit 6330775

Please sign in to comment.