Python JSON数据序列化

Python如果要将一个字典数据转化为Json格式,对数据类型有一定的要求,默认支持:

    +-------------------+---------------+
    | Python            | JSON          |
    +===================+===============+
    | dict              | object        |
    +-------------------+---------------+
    | list, tuple       | array         |
    +-------------------+---------------+
    | str               | string        |
    +-------------------+---------------+
    | int, float        | number        |
    +-------------------+---------------+
    | True              | true          |
    +-------------------+---------------+
    | False             | false         |
    +-------------------+---------------+
    | None              | null          |
    +-------------------+---------------+

如果要支持其他的类型,需要自定义JSONEncoder才能实现。例如:

import json
from decimal import Decimal
from datetime import datetime

data = [
    {"id": 1, "name": "tom", "age": 1, 'size': Decimal("9.3"), 'ctime': datetime.now()},
    {"id": 2, "name": "jerry", "age": 2, 'size': Decimal("0.5"), 'ctime': datetime.now()},
]
res = json.dumps(data)
print(res)

输出结果显示报错:

TypeError: Object of type Decimal is not JSON serializable

原因就是Decimal不能被序列化。

解决办法是实现json.JSONEncoder

import json
from decimal import Decimal
from datetime import datetime

data = [
    {"id": 1, "name": "tom", "age": 1, 'size': Decimal("9.3"), 'ctime': datetime.now()},
    {"id": 2, "name": "jerry", "age": 2, 'size': Decimal("0.5"), 'ctime': datetime.now()},
]


class MyJSONEncoder(json.JSONEncoder):
    def default(self, o):
        if type(o) == Decimal: # 当原始数据中的数据类型为Decimal
            return str(o)
        elif type(o) == datetime: # 当原始数据中的数据类型为Decimal
            return o.strftime("%Y-%M-%d") # 只获取年月日, 并转为字符串
        return super().default(o)


res = json.dumps(data, cls=MyJSONEncoder)
print(res)

其中的type(o)表示,json数据中的所有的数据类型。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值