I have a basic dict as follows:
sample = {}
sample[\'title\'] = \"String\"
sample[\'somedate\'] = somedatetimehere
My solution (with less verbosity, I think):
def default(o):
if type(o) is datetime.date or type(o) is datetime.datetime:
return o.isoformat()
def jsondumps(o):
return json.dumps(o, default=default)
Then use jsondumps
instead of json.dumps
. It will print:
>>> jsondumps({'today': datetime.date.today()})
'{"today": "2013-07-30"}'
I you want, later you can add other special cases to this with a simple twist of the default
method. Example:
def default(o):
if type(o) is datetime.date or type(o) is datetime.datetime:
return o.isoformat()
if type(o) is decimal.Decimal:
return float(o)