Python2.7 json conversion date processing example, python2.7json
Python2.7 integrates the json processing (simplejson), but in actual applications, the data queried from mysql usually has a date format. At this time, an error is reported:
TypeError: datetime. datetime (2007, 7, 23, 12, 24, 25) is not JSON serializable
It indicates that there was a problem with the date conversion, and then the solution was found online.
Import jsonfrom datetime import date, datetimedef _ default (obj): if isinstance (obj, datetime): return obj. strftime ('% Y-% m-% dT % H: % M: % s') elif isinstance (obj, date): return obj. strftime ('% Y-% m-% D') else: raise TypeError (' % r is not JSON serializable '% obj) print json. dumps ({'D': datetime. now (), 'today': date. today (), 'x': 111}, default = __default)
The following method is used to serialize a mysql dataset.
Conn?self.getconnection({{cursor=conn.cursor({{cursor.exe cute (sqlText, params); result = cursor. fetchall () jsonstr = json. dumps (myresult, default =__ default) print jsonstr
The key point is to overwrite the default method.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.