python encoder_python JSONencoder

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值