咱们在Python的json.JSONEncoder类
中能够查看Python数据序列化为JSON格式的数据时数据类型的对应关系:python
class JSONEncoder(object): """Extensible JSON <http://json.org> 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 | +-------------------+---------------+ pass # 其余方法省略
可是实际中咱们也常常会遇到不能直接进行JSON序列化的Python数据,好比说datetime
与Decimal
类型的数据,这时就须要咱们先把这两种格式的数据转换为Python的str
,而后再进行JSON序列化操做。json
咱们在进行json.dumps()
操做的时候能够指定进行序列化的类:code
import json from datetime import datetime from datetime import date #对含有日期格式数据的json数据进行转换 class JsonCustomEncoder(json.JSONEncoder): def default(self, field): if isinstance(field,datetime): return field.strftime('%Y-%m-%d %H:%M:%S') elif isinstance(field,date): return field.strftime('%Y-%m-%d') else: return json.JSONEncoder.default(self,field) d1 = datetime.now() dd = json.dumps(d1,cls=JsonCustomEncoder) print(dd)
其实,本质上仍是利用了strftime
方法:ci
from datetime import datetime i = datetime.strftime(i,'%Y-%m-%d')
对于Decimal
类型的数据咱们能够利用Python的decimal模块
先将其转为str
:string
import decimal price = str(decimal.Decimal(price).quantize(decimal.Decimal('0.00')))
而后把获得的结果再进行序列化便可。class