Inconsistent encoding of the empty string
jixam opened this issue · comments
Before I dig further, is this expected behavior?
An object stringifying to the empty string encodes to different JSON depending on its constructor:
Test program
use Cpanel::JSON::XS;
use v5.36;
{
package E;
use overload '""' => sub { "" };
sub new1($class) { bless [undef] => $class };
sub new2($class) { bless \(my $dummy=undef), $class; };
}
my $JSON = Cpanel::JSON::XS->new->convert_blessed;
say $JSON->encode( E->new1() );
say $JSON->encode( E->new2() );
Output
""
null
We follow upstream
Hmm, this is a stringification overload which I believe upstream does not support?
(With TO_JSON
it works as expected, both here and in upstream – but there is no TO_JSON
in the test program)
Maybe the below is a better demonstration: with otherwise identical classes, the output is different between TO_JSON
and overload '""'
.
The empty stringification result is being replace with null
here but I don't know how to modify the condition for this situation.
Test program 2
use Cpanel::JSON::XS;
use v5.36;
{
package J;
sub TO_JSON { ${$_[0]} }
sub new($class, $string) { bless \(my $dummy = $string) => $class };
}
{
package O;
use overload '""' => sub { ${$_[0]} };
sub new($class, $string) { bless \(my $dummy = $string) => $class };
}
my $JSON = Cpanel::JSON::XS->new->convert_blessed;
say $JSON->encode( J->new("") ); # ""
say $JSON->encode( O->new("") ); # null