sciurius / perl-JSON-Relaxed

An extension of JSON that allows for better human-readability.
0 stars 0 forks source link

encode method encodes blessed objects as their stringification, or overloaded stringification #4

Open jwrightecs opened 4 months ago

jwrightecs commented 4 months ago

When encountering a blessed object in a Perl structure, JSON::Relaxed encodes it as a JSON string, using either the default stringification (Class::Name=REFTYPE(0x0abcd09abc)) or any overloaded stringification "".

It should probably have an option to either use the objects TO_JSON (TO_RJSON?) or FREEZE method ("allow_blessed"), encode it as a null ("allow_blessed"), or fail to encode

use strict;
use warnings;
use JSON::PP;
use JSON::Relaxed;
my $j = JSON::PP->new->convert_blessed;
my $rj = JSON::Relaxed->new;

package An::Object {
    sub TO_JSON {
        my $self = shift;
        +{ %$self };
    }
};

my $obj = bless { test => 'data' }, 'An::Object';
my $json_string = $j->encode( $obj );
my $rjson_string = $rj->encode( data => $obj );

print "JSON $json_string\n";
print "RJSON $rjson_string\n";

outputs

JSON {"test":"data"}
RJSON "An::Object=HASH(0x55eaeb9c7e48)"
sciurius commented 4 months ago

I've checked in an enhancement to use the TO_JSON (or FREEZE) method for objects. I don't think it is neccessary to add conditionals convert_blessed/allow_blessed. Do you?

jwrightecs commented 4 months ago

It would probably go against the relaxed spirit of the module, so no,