[Catalyst] Noob hoping for help encoding mysql datetime fields for JSON

Tomas Doran bobtfish at bobtfish.net
Fri Mar 16 08:10:46 GMT 2012


On 15 Mar 2012, at 21:38, Steve Seremeth wrote:
> 
> If I simply add the column to the API controller here:
> 
> <snip>
>     $data{rows}  = [
>         map { +{
>             id => $_->id,
>             cell => [
>                 $_->id,
>                 $_->title,
>                 $_->rating,
>                 $_->author_list,
>                 $_->created,
>             ]
>         } } $paged_rs->all
>     ];
> </snip>
> 
> The app throws this:
> 
> Content-Type application/json had a problem with your
>       request.
> 
> ***ERROR***
> encountered object '2012-02-29T17:16:27', but neither
>       allow_blessed enabled nor TO_JSON method available on it at
>       /usr/local/share/perl/5.12.4/Catalyst/Action/Serialize/JSON.pm
>       line 39.
> 
> 
> And I realize I'm not serializing the timestamp appropriately (and how data with colons are bound to cause issues in JSON)...  but this simple thing is what I haven't been able to solve.

The JSON encoder will handle escaping for you, so colons, quotes, backslashes or whatever aren't an issue.

What's happening here is that you have a 'DateTime' object, and the JSON encoder is puking on encoding it, as it's an object.

DateTime objects stringily by default, which is why you get: encountered object '2012-02-29T17:16:27'.. This error message is crap really - it doesn't make it clear that it's an object which has been stringified, and doesn't tell you which class is at fault!!

So, the simplest fix is:

> cell => [
>                 $_->id,
>                 $_->title,
>                 $_->rating,
>                 $_->author_list,
>                 $_->created."",
>             ]

Adding the ."" means that the object gets explicitly stringified, using whatever the default formatter is (giving you something ISO8601ish by default).

You can, of course, be a little more creative / flexible with the formatting if you want or need to be - checkout the DateTime::Format docs :)

Cheers
t0m




More information about the Catalyst mailing list