Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Schema to support TO_JSON methods #43

Open
bpj opened this issue May 12, 2021 · 2 comments
Open

Schema to support TO_JSON methods #43

bpj opened this issue May 12, 2021 · 2 comments

Comments

@bpj
Copy link

bpj commented May 12, 2021

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?

@bpj
Copy link
Author

bpj commented Feb 23, 2024

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?

perlpunk added a commit that referenced this issue Feb 25, 2024
perlpunk added a commit that referenced this issue Feb 25, 2024
perlpunk added a commit that referenced this issue Feb 25, 2024
perlpunk added a commit that referenced this issue Feb 25, 2024
@perlpunk
Copy link
Owner

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants