NAME
JSON::UnblessObject - unbless object using JSON spec like Cpanel::JSON::XS::Type
SYNOPSIS
use JSON::UnblessObject qw(unbless_object);
use Cpanel::JSON::XS::Type;
package SomeEntity {
sub new {
my ($class, %args) = @_;
return bless \%args, $class
}
sub a { shift->{a} }
sub b { shift->{b} }
}
my $entity = SomeEntity->new(a => 123, b => 'HELLO');
unbless_object($entity, { a => JSON_TYPE_INT });
# => { a => 123 }
unbless_object($entity, { b => JSON_TYPE_STRING });
# => { b => 'HELLO' }
unbless_object($entity, { a => JSON_TYPE_INT, b => JSON_TYPE_STRING });
# => { a => 123, b => 'HELLO' }
DESCRIPTION
JSON::UnblessObject is designed to assist with JSON encode. For example, an blessed object can be encoded using JSON spec:
my $json = Cpanel::JSON::XS->new->canonical;
sub encode_json {
my ($data, $spec) = @_;
$data = unbless_object($data, $spec) if blessed $data;
$json->encode($data, $spec)
}
encode_json($entity, { a => JSON_TYPE_INT });
# => {"a":123}
encode_json($entity, { b => JSON_TYPE_STRING });
# => {"b":"HELLO"}
encode_json($entity, { a => JSON_TYPE_INT, b => JSON_TYPE_STRING }),
# => {"a":123,"b":"HELLO"}
RESOLVERS
The unbless_object function performs a resolver for a given object type.
- resolve_arrayref($object, $spec)
-
When
$specisARRAYREF, executes this function.$objectmust either have@{}overload or be an iterator withnextmethod. If$specis[JSON_TYPE_STRING, JSON_TYPE_STRING], then resolve like thislist($object)->[0], list($object)->[1].listfunction is an internal utility function that converts$objectto arrayref. - resolve_hashref($object, $spec)
-
When
$specisHASHREF, executes this function. If$specis{ foo => JSON_TYPE_STRING, bar => JSON_TYPE_STRING }, then resolve like this{ foo => $object->foo, bar => $object->bar }. - resolve_json_type_arrayof($object, $spec)
-
When
$specisCpanel::JSON::XS::Type::ArrayOf, executes this function.$objectmust either have@{}overload or be an iterator withnextmethod. - resolve_json_type_hashof($object, $spec)
-
When
$specisCpanel::JSON::XS::Type::HashOf, executes this function.$objectrequiresJSON_KEYSfunction.JSON_KEYSmethod is a whitelist of$objectthat are allowed to be published as JSON.package SomeEntity { sub new { my ($class, %args) = @_; return bless \%args, $class } sub secret { shift->{secret} } sub a { shift->{a} } sub b { shift->{b} } # Do not include keys that cannot be published like `secret` sub JSON_KEYS { qw/a b/ } } my $entity = SomeEntity->new(a => 1, b => 2, secret => 'XXX'); unbless_object($entity, json_type_hashof(JSON_TYPE_STRING)) # => { a => 1, b => 2 } - resolve_json_type_anyof($object, $spec)
-
When
$specisCpanel::JSON::XS::Type::AnyOf, executes this function. If$objectis available as array, it is resolved as array; if it is available as hash, it is resolved as hash; otherwise, it is resolved as scalar.
SEE ALSO
LICENSE
Copyright (C) kfly8.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
AUTHOR
kfly8 <kfly@cpan.org>