How can I pass arguments to a default handler function while converting data to JSON using Bottle's json_dumps?
EDIT: I missed a point where I convert the data from
json_dumps, back to the previous format usingjson_loads. The reason I usejson_dumpsis because i need to convert thedatetimeformat tostring
I have the result of a MySQL query as list of tuples:
data = [(u'user1', u'Topic1', datetime.datetime(2015, 8, 3, 23, 55), 2.0, 5), (u'user2', u'Topic2', datetime.datetime(2015, 8, 4, 23, 55), 3.0, 5)]
It contains some data in datetime format. And I send this data as response to an AJAX call, in JSON format, because of which I perform json_dumps on it.
Now, I can't simply perform json_dumps(data) as it gives this error:
TypeError: datetime.datetime(2015, 8, 3, 23, 55) is not JSON serializable
So, I define this handler function and use it as follows:
def dataHandler(obj):
if isinstance(obj, datetime):
return obj.strftime('%Y-%m-%d %H:%M')
json_dumps(data, default=dataHandler)
This works fine and the output is:
'[["user1", "Topic1", "2015-08-03 23:55", 2.0, 5], ["user2", "Topic2", "2015-08-04 23:55", 3.0, 5]
Now at different points in my code, for different data, I need different formats of datetime. So, I redefined the function like this:
def dataHandler(obj, showTime='no'):
if isinstance(obj, datetime):
if str(showTime).lower() == 'no':
return obj.strftime('%Y-%m-%d')
elif str(showTime).lower() == 'yes':
return obj.strftime('%Y-%m-%d %H:%M')
Now if I perform json_dumps(data, default=dataHandler), it works properly, considers showTime as no and gives output same as above.
The problem comes when I try to pass it an argument:
json_dumps(data, default=dataHandler('Yes'))
It gives this error:
TypeError: datetime.datetime(2015, 8, 10, 23, 55) is not JSON serializable
How can I have different such cases defined in the same function?
Thanks.