pwilding
pwilding

Reputation: 33

Unable to serialize datetime.datetime object in dictionary to JSON using python and trac

I have a list of dictionaries (each dictionary representing 1 record of an SQL query) which I am trying to serialize as JSON. There are several datetime.date and datetime.datetime objects in these dictionaries which are proving difficult to serialize. Initially, the error message is:

TypeError: datetime.date(2012, 5, 23) is not JSON serializable

After adding a handler to the json.dumps call the error message is:

TypeError: date_handler() takes exactly 1 argument (2 given)

date_handler looks like this:

    def date_handler(obj):
        return obj.isoformat() if hasattr(obj, 'isoformat') else obj

I'm running this as part of a Trac plugin however I think this is just an isolated python issue but have no idea what to do to sort it - does anyone have any ideas?

Upvotes: 0

Views: 4180

Answers (2)

pwilding
pwilding

Reputation: 33

I solved this by applying .isoformat() fields that were dates or timestamps in the dictionary as I'm importing the data from a database and so know what the field types are beforehand, thanks for your help!

Upvotes: 2

hasienda
hasienda

Reputation: 2390

See a solution from the Django domain.

Upvotes: 0

Related Questions