json_util.py 938 B

1234567891011121314151617181920212223242526272829303132333435
  1. # coding=utf-8
  2. from datetime import datetime, date
  3. try:
  4. import simplejson as json
  5. except ImportError:
  6. import json
  7. # 方式1
  8. def json_time_default(obj):
  9. """
  10. >>> data = json.dumps(datetime.now(), default=json_time_default)
  11. """
  12. if isinstance(obj, datetime):
  13. return obj.strftime('%Y-%m-%dT%H:%M:%S')
  14. elif isinstance(obj, date):
  15. return obj.strftime('%Y-%m-%d')
  16. else:
  17. raise TypeError('%r is not JSON serializable' % obj)
  18. # 方式2:重写JSONEncoder类,此类负责编码,主要是通过其default函数进行转化
  19. class date_time_encoder(json.JSONEncoder):
  20. """
  21. >>> data = json.dumps(datetime.now(), cls=date_time_encoder)
  22. """
  23. def default(self, o):
  24. if isinstance(o, datetime):
  25. return o.strftime('%Y-%m-%dT%H:%M:%S')
  26. elif isinstance(o, date):
  27. return o.strftime('%Y-%m-%d')
  28. return json.JSONEncoder.default(self, o)