makamaka / JSON

perl implementation of JSON encoder/decoder
42 stars 40 forks source link

Create a 'use_overload' option #36

Open rkleemann opened 6 years ago

rkleemann commented 6 years ago

Some objects overload numification or stringification, but don't have a TO_JSON method. It would be nice for those objects to be encoded without having to monkey patch a TO_JSON method for them. The one that pops to mind is URI, but there are others.

The following code would go somewhere in object_to_json, and should work for this.

if ( $use_overload && overload::Overloaded($obj) ) {
    if ( my $overload = overload::Method( $obj, '0+' )
                     || overload::Method( $obj, '""' ) )
    {
        return $self->value_to_json( $obj->$overload() );
    }
}

There would also be a sub to turn on/off the feature, and require overload; when it is enabled.

charsbar commented 5 years ago

You know better about the data struture, and which objects in the structure need to be converted, than JSON modules. I think TO_JSON is better and gives you more freedom, but if you do think this is nice, please send an email to the author of JSON::XS and ask him. If you manage to convince him to implement it, JSON::PP (and JSON.pm) will do the same.