Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mojo::JSON: encode core boolean values as json bools #2192

Merged
merged 1 commit into from
Aug 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading