Skip to content

Instantly share code, notes, and snippets.

@ayuLiao
Last active June 15, 2018 08:48
Show Gist options
  • Save ayuLiao/b2b71d9f892601a457208ae499f86f4f to your computer and use it in GitHub Desktop.
Save ayuLiao/b2b71d9f892601a457208ae499f86f4f to your computer and use it in GitHub Desktop.
json格式化时,添加自己自定义动作
import json
import datetime
# json格式化时自定义动作
class CJsonEncoder(json.JSONEncoder):
def default(self,obj):
if isinstance(obj,datetime.datetime):
return obj.strftime('%Y-%m-%d %H:%M:%S')
elif isinstance(obj,datetime.date):
return obj.strftime('%Y-%m-%d')
else:
return json.JSONEncoder.default(self,obj)
if __name__ == '__main__':
noticList = [{'1':1,'2':2,'d':datetime.datetime.now()}]
print(json.dumps(noticList, cls=CJsonEncoder))
# 输出:
#[{"d": "2018-06-15 16:47:45", "2": 2, "1": 1}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment