22

I have a class in Python for retrieving all the columns in a table and return a JSON with this data.

The problem is at least one of those columns is a datetime and I can't seem to understand how to serialize the columns so I can generate a valid JSON.

My class is as follows:

class GetTodos(Resource):
    def get(self):
        con = cx_Oracle.connect('brunojs/[email protected]/orcl')
        cur = con.cursor()
        cur.execute("select * from organite_repository")
        r = [dict((cur.description[i][0], value) \
                for i, value in enumerate(row)) for row in cur.fetchall()]
        cur.connection.close()
        return (r[0] if r else None) if None else r 

Any hints on this?

0

2 Answers 2

54

JSON doesn't have a default datetime type, so this is why Python can't handle it automatically. So you need to make the datetime into a string one way or another. I think the best way is to write a custom handler to help the json module.

import datetime
import json

def datetime_handler(x):
    if isinstance(x, datetime.datetime):
        return x.isoformat()
    raise TypeError("Unknown type")

json.dumps(data, default=datetime_handler)
Sign up to request clarification or add additional context in comments.

10 Comments

I updated this with raise x for my case.
Use json.JSONEncoder.default = datetime_handler to parse datetime automatically without using default=datetime_handler every time.
I'm getting a TypeError with this answer, that says datetime_handler accepts 1 argument but JSON is trying to hand it 2.
Have just tried my original answer with Python 2.6.9 and 3.4.1 and it works with both. If you are following the answer from @ChaimG you may need to specify a self parameter as well because you've overriding this: docs.python.org/3/library/json.html#json.JSONEncoder.default
maybe would be wise to update json module and allow datetime conversion ?
|
4

A simple way to do it is to cast your data to string. That way, you will be able to dump with json.

>>> datetime.now()
datetime.datetime(2016, 3, 8, 11, 37, 24, 123639)

>>> str(datetime.now())
'2016-03-08 11:37:27.511053'

But, you could also implement a serializer to transform the data as you want.

2 Comments

it should be like str(datetime.datetime.now()), because: [ERROR] AttributeError: module 'datetime' has no attribute 'now'
@omalave datetime.now() is possible provided you import datetime in this way --> >>>from datetime import datetime >>>datetime.now() >>> datetime.datetime(2022, 6, 20, 15, 31, 27, 900332)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.