YAML-PP-p5
YAML-PP-p5 copied to clipboard
Schema to support TO_JSON methods
What about a schema which recognises TO_JSON methods the same way as the JSON modules do? That would be a useful compromise I think. Would it be hard to implement?
Four years later and it has come to the point that I really need either this or a way to tell the dumper to honor overloaded hash/array dereferencing. I have mucked around a bit and think I understand how a schema might implement the latter. What do you think?
I had an idea how to make this configurable. How about this code:
subtest serializer => sub {
my $perl = YAML::PP::Schema::Perl->new(
serializer => 'TO_JSON',
);
my $yp = YAML::PP->new(
schema => [qw/ + /, $perl],
);
my $o = bless [3,4], "Dice";
my $data = { dice => $o };
*Dice::TO_JSON = sub {
my ($self) = @_;
return join 'd', @$self;
};
my $yaml = $yp->dump_string($data);
my $exp = <<'EOM';
---
dice: 3d4
EOM
is $yaml, $exp, "TO_JSON returns string";
no warnings 'redefine';
*Dice::TO_JSON = sub {
my ($self) = @_;
return { '__dice__' => [@$self] };
};
$yaml = $yp->dump_string($data);
$exp = <<'EOM';
---
dice:
__dice__:
- 3
- 4
EOM
is $yaml, $exp, "TO_JSON returns hash";
};
I pushed this to https://github.com/perlpunk/YAML-PP-p5/tree/to-json if you want to try it out.