Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

datetime.datetime is not JSON serializable [duplicate]

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?

like image 308
Bruno Fernandes Avatar asked Mar 08 '16 14:03

Bruno Fernandes


People also ask

How to overcome datetime datetime not JSON serializable?

The Python "TypeError: Object of type datetime is not JSON serializable" occurs when we try to convert a datetime object to a JSON string. To solve the error, set the default keyword argument to str in your call to the json. dumps() method.

Is not JSON serializable?

The Python "TypeError: Object of type function is not JSON serializable" occurs when we try to serialize a function to JSON. To solve the error, make sure to call the function and serialize the object that the function returns.

How do you serialize a date in python?

Serialize datetime by converting it into String You can convert dateTime value into its String representation and encode it directly, here you don't need to write any encoder. We need to set the default parameter of a json. dump() or json. dumps() to str like this json.

How does JSON store date time?

JSON does not have a built-in type for date/time values. The general consensus is to store the date/time value as a string in ISO 8601 format.


2 Answers

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)
like image 105
Michael Mulqueen Avatar answered Sep 17 '22 17:09

Michael Mulqueen


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.

like image 24
feliperuhland Avatar answered Sep 17 '22 17:09

feliperuhland