[Catalyst] Cross-link: How do I turn Moose objects into JSON for use in Catalyst?

Evan Carroll me at evancarroll.com
Tue Aug 3 17:11:15 GMT 2010


> The documentation  isn't clear on how, but this implies some combination of
> these flags (probably setting both to true) should do the "encoding the
> reference as if it weren't blessed" thing.

No, allow_blessed(1) means it will not die, it will instead print out
the totally useless string 'null'. This is technically allowing a
blessed scalar. However, convert_blessed, is a total misnomer as
nothing is /converted/. All that happens is the method TO_JSON is
called.

ecarroll at rda:~$ perl -MJSON::XS -E'my $o = bless { foo=>'bar' }; say
JSON::XS->new->encode( $o );'
encountered object 'main=HASH(0x7b8df0)', but neither allow_blessed
nor convert_blessed settings are enabled at -e line 1.

ecarroll at rda:~$ perl -MJSON::XS -E'my $o = bless { foo=>'bar' }; say
JSON::XS->new->allow_blessed(1)->encode( $o );'
null
ecarroll at rda:~$ perl -MJSON::XS -E'my $o = bless { foo=>'bar' }; say
JSON::XS->new->allow_blessed(1)->convert_blessed(1)->encode( $o );'
null

In this example the object is blessed in the default package main,
where TO_JSON is called.

ecarroll at rda:~$ perl -MJSON::XS -E'my $o = bless { foo=>'bar' }; sub
TO_JSON { "hi" }; say
JSON::XS->new->allow_blessed(1)->convert_blessed(1)->encode( $o );'
"hi"


But yes, ideally /convert_blessed/ would do what I want rather than
just call a sub that expects me to do it. My handy old XXX.pm does
this right:

ecarroll at rda:~$ perl -E'my $o = bless { foo=>'bar' }; use XXX; XXX $o'
--- !!perl/hash:main
foo: bar
...
  at -e line 1

-- 
Evan Carroll - me at evancarroll.com
System Lord of the Internets
web: http://www.evancarroll.com
ph: 281.901.0011



More information about the Catalyst mailing list