在解析含有Decimal的元素时,json会报错:
TypeError: Decimal is not JSON serializable
参考一下19.2. json — JSON encoder and decoder中对dump参数的描述:
If specified, default should be a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError. If not specified, TypeError is raised.
因此通过声明default函数可以解决Decimal无法Json Serialize的问题,代码如下:
import json
from decimal import Decimal
def decimal_default(obj):
if isinstance(obj, Decimal):
return float(obj)
raise TypeError
d = {"Num": Decimal(5,5)}
print(json.dumps(d, default=decimal_default))
设置ensure_ascii = False
即:
import json
d = {"Text": "你好"}
print(json.dumps(d, ensure_ascii = False))
import json
from decimal import Decimal
from datetime import date
from datetime import datetime
def json_default(obj):
if isinstance(obj, Decimal):
return float(obj)
elif isinstance(obj, date):
return obj.isoformat()
elif isinstance(obj, datetime):
return obj.strftime("%Y-%m-%d %H:%M:%S")
raise TypeError
json.dumps(d, default=json_default, ensure_ascii = False)
参考
Python to JSON Serialization fails on Decimal - StackOverflow