Python json.dumps可以通过encoder选项自定义转换方式。
默认的encoder(json.JSONEncoder) 只对部分进行了转化:
"""Extensible JSON encoder for Python data structures.
Supports the following objects and types by default:
+-------------------+---------------+
| Python | JSON |
+===================+===============+
| dict | object |
+-------------------+---------------+
| list, tuple | array |
+-------------------+---------------+
| str | string |
+-------------------+---------------+
| int, float | number |
+-------------------+---------------+
| True | true |
+-------------------+---------------+
| False | false |
+-------------------+---------------+
| None | null |
+-------------------+---------------+
To extend this to recognize other objects, subclass and implement a
``.default()`` method with another method that returns a serializable
object for ``o`` if possible, otherwise it should call the superclass
implementation (to raise ``TypeError``).
如文档描述,自定义需要重写default方法,如django 中Jsonresponse方法默认的encoder DjangoJSONEncoder
from django.core.serializers.json importDjangoJSONEncoderclassDjangoJSONEncoder(json.JSONEncoder):"""JSONEncoder subclass that knows how to encode date/time, decimal types, and
UUIDs."""
defdefault(self, o):#See "Date Time String Format" in the ECMA-262 specification.
ifisinstance(o, datetime.datetime):
r=o.isoformat()ifo.microsecond:
r= r[:23] + r[26:]if r.endswith('+00:00'):
r= r[:-6] + 'Z'
returnrelifisinstance(o, datetime.date):returno.isoformat()elifisinstance(o, datetime.time):ifis_aware(o):raise ValueError("JSON can't represent timezone-aware times.")
r=o.isoformat()ifo.microsecond:
r= r[:12]returnrelifisinstance(o, datetime.timedelta):returnduration_iso_string(o)elifisinstance(o, (decimal.Decimal, uuid.UUID, Promise)):returnstr(o)else:return super().default(o)
用法 json.dumps({...},cls=DjangoJSONEncoder)