JSON icon indicating copy to clipboard operation
JSON copied to clipboard

Create a 'use_overload' option

Open rkleemann opened this issue 6 years ago • 1 comments

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.

rkleemann avatar Apr 13 '18 17:04 rkleemann

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.

charsbar avatar Dec 24 '18 06:12 charsbar