python json序列化问题
程序员文章站
2024-02-03 11:17:28
...
- TypeError: Object of type ‘Decimal’ is not JSON serializable
import decimal
import json
class CJsonEncoder(json.JSONEncoder):
"""
json格式化问题,解决python不能序列化问题
"""
def default(self, obj):
if isinstance(obj, decimal.Decimal):
return float(obj)
else:
return json.JSONEncoder.default(self, obj)
- TypeError: Object of type ‘type’ is not JSON serializable
import json
class BytesEncoder(json.JSONEncoder):
def default(self,obj):
if isinstance(obj,bytes):
return str(obj,encoding='utf-8')
return json.JSONEncoder.default(self,obj)
- TypeError: datetime.datetime(····) is not JSON serial
import json
from datetime import datetime, date
class CJsonEncoder(json.JSONEncoder):
"""
json格式化问题,解决python时间格式不能序列化问题
"""
def default(self, obj):
if isinstance(obj, datetime):
return obj.strftime('%Y-%m-%d %H:%M:%S')
elif isinstance(obj, date):
return obj.strftime("%Y-%m-%d")
else:
return json.JSONEncoder.default(self, obj)
使用方法
import json
data = {"...":"..."}
json.dumps(data, cls=CJsonEncoder)