++ed by:
1 non-PAUSE user
Author image Paul Williams


Moo::Role::ToJSON - a Moo role for a TO_JSON method


    package My::Message;
    use Moo;
    with 'Moo::Role::ToJSON';

    has feel_like_sharing => (is => 'rw', default => 0);
    has message => (is => 'ro', default => 'Hi Mum!');
    has secret  => (is => 'ro', default => 'I do not like eating healthily');

    sub _build_serializable_attributes { [qw/message secret/] }

    # optional instance method to selectively serialize an attribute
    sub is_attribute_serializable {
        my ($self, $attr) = @_;

        if ($attr eq 'secret' && !$self->feel_like_sharing) {
            # returning a false value won't include attribute when serializing
            return 0;

        return 1;


    # t/test.t
    use Test2::Bundle::More;
    use Test2::Tools::Compare;

    my $message = My::Message->new();
    is $message->TO_JSON => {message => 'Hi Mum!'};

    is $message->TO_JSON =>
        {message => 'Hi Mum!', secret => 'I do not like eating healthily'};


Moo::Role::ToJSON is a Moo::Role which provides a "TO_JSON" method for your classes. The TO_JSON method will returns a HASH reference of all the "serializable_attributes". It is your responsibility to ensure the attributes in your classes can be directly encoded into JSON.


Moo::Role::ToJSON implements the following attributes.


    # optionally override serialized attributes on instantiation
    my $message = My::Message->new(
        serializable_attributes => [qw/feel_like_sharing message secret/]

An ARRAY reference of attributes to serialize. Typically this would be set directly in your class, but the default attributes can be overridden per instance as in the example above.

This attribute is provided as a lazy Moo attribute, as such, the "_build_serializable_attributes" builder should be used to set the default serializable attributes.

All of the attributes must return data that can be directly encoded into JSON.


Moo::Role::ToJSON implements the following methods.


    sub _build_serializable_attributes { [qw/message secret/] }

The builder method returning the list of attributes to serialize. This method must return an ARRAY reference.


    use Mojo::JSON 'encode_json';

    my $message = My::Message->new();
    say encode_json $message;

Returns a HASH reference representing your object. This is intended to be used by any encode_json function that checks for the availability of the TO_JSON method for blessed objects.


See t/complete.t for a complete example.


Paul Williams <kwakwa@cpan.org>


Copyright 2018- Paul Williams


This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.


DBIx::Class::Helper::Row::ToJSON, Moo::Role.