''''
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import json as default_json
from json.encoder import JSONEncoder
class JsonEncoder(JSONEncoder):
def default(self, o):
if isinstance(o, object):
return o.__dict__
return JSONEncoder.default(self, o)
class Json(object):
@staticmethod
def dumps(response, ensure_ascii=True):
return default_json.dumps(response, ensure_ascii=ensure_ascii, cls=JsonEncoder)
''''
import json from json.encoder import JSONEncoder from datetime import datetime,date class Jsonencoder(JSONEncoder): def default(self, field): if isinstance(field,datetime): #如果field是日期类型 return field.strftime("%Y-%m-%d %H:%M:%S") elif isinstance(field,date): return field.strftime("%Y-%m-%d") elif isinstance(field,object): return field.__dict__ else: return json.JSONEncoder.default(self,field) class Baseobj(): def __init__(self): self.status=True self.message=None self.data=None self.name="hello" #json序列化只能dumps py的基本数据类型:如字典,列表、数字,如日期、对象的话需要做特殊处理 aa=Baseobj() print("----------",aa) #<__main__.Baseobj object at 0x000002D941E97F48> data_obj={ "k1":132, "k2":datetime.now(), "k3":Baseobj(), "k4":"hao",
"k5":["as", 2, "sadf"]
} ds=json.dumps(data_obj,cls=Jsonencoder) print(ds)
'''
{"k1": 132,
"k2": "2021-02-24 19:40:20",
"k3": {"status": true, "message": null, "data": null, "name": "hello"},
"k4": "hao",
"k5": ["as", 2, "sadf"]
}
'''