Sérgio
Sérgio

Reputation: 7279

perl mongDB to_json howto convert an ISODate, What is the right way to serialize Datetime object

I have a mongoDB with :

my $data = $newspapers->find_one({_id => 2000});

last_mdb_update is a datetime in $data and is a ISODate in mongoDB

$result = to_json( $data, { ascii => 1, utf8 => 1, pretty => 1 } );

I got an error: encountered object '2013-11-06T06:45:16', but neither allow_blessed nor convert_blessed settings are enabled

Note: I can do, to fix and serialize, but is an ugly workaround and just works for that field:

$data->{last_mdb_update} = ''.$data->{last_mdb_update};

$result = to_json( $data, {ascii => 1, utf8 => 1, pretty => 1, convert_blessed => 1 } ); says (...) nor TO_JSON method available

what is TO_JSON method for ISODate ?

Upvotes: 0

Views: 574

Answers (2)

Sérgio
Sérgio

Reputation: 7279

sub DateTime::TO_JSON {
    { "".shift }
}

my $result = to_json( $data, { utf8 => 1, pretty => 1, convert_blessed => 1 } );

works !

Upvotes: 0

friedo
friedo

Reputation: 67028

By default, MongoDB ISODate objects are returned as DateTime objects in the Perl MongoDB driver. The error you are getting sounds like it is coming from the JSON serialization library, which is unrelated to MongoDB.

JSON has no native datetime type, so if you want to serialize it you'll need to convert the DateTime object to some kind of number or string first.

Upvotes: 1

Related Questions