makamaka / JSON

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

Allow stringification of objects #37

Closed rkleemann closed 5 years ago

rkleemann commented 6 years ago

An idea I had was to allow the stringification of objects in some form that comes out as a readable string, which could be reinterpreted back as the object.

Consider the following object:

my $obj = bless( { foo => 1, bar => 'baz' }, 'My::Object' );

After a say $json->encode([$obj]); with the right options enabled, it would produce something like:

["My::Object={\"bar\":\"baz\",\"foo\":1}"]

The code seems fairly straightforward, going into object_to_json:

if ( $stringify ) {
    my $string = ref($obj);
    my $type = Scalar::Util::reftype($obj);
    if ( $type eq 'SCALAR' ) {
        $string .= '=' . $self->value_to_json($$obj);
    }
    elsif ( $type eq 'ARRAY' ) {
        $string .= '=' . $self->array_to_json($obj);
    }
    elsif ( $type eq 'HASH' ) {
        $string .= '=' . $self->hash_to_json($obj);
    }
    return $self->value_to_hash($string);
}
charsbar commented 5 years ago

If you really need such information, you should use Data::Dumper, Data::Dump, Data::Printer, or whatever you like to dump the content of an object. If you still need it as a JSON text, put that dump into an array, and pass its reference to encode_json(). If you use the latest JSON modules, you can put the dump directly into encode_json(). No need for extra code.

The latest JSON backends also have allow_tags() option, and filter_json_object callback, if you need finer control.