如何序列化python中不支持序列化數據類型?

序列化對象

使用__dict__方法把對象轉換成字典

import json

class Student(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age


if __name__ == '__main__':
    s = Student("Tom", 23)

    # 序列化
    ret = json.dumps(s, default=lambda obj: obj.__dict__)
    print('ret=%s'%ret,'type of ret = %s'%type(ret))
    # {"name": "Tom", "age": 23}

    # 反序列化
    def obj2student(d):
        return Student(d["name"], d["age"])

    s2 = json.loads(ret, object_hook=obj2student)
    print('s2=%s'%s2,'type of ret = %s'%type(ret))
    # <__main__.Student object at 0x101c7e518>

ret={“name”: “Tom”, “age”: 23} type of ret = <class ‘str’>
s2=<main.Student object at 0x0000018D2D3BC438> type of ret =<class ‘str’>

修改json源碼實現序列化不可序列化的字段

首先我們先看下json的一個簡單的序列化,因爲中文在ASCII碼中是無法正確顯示的。

import json

res1 = json.dumps({"name":"名字","age":18})
print(res1)
res2 = json.dumps({"name":"名字","age":18},ensure_ascii=False)
print(res2)

{“name”: “\u540d\u5b57”, “age”: 18} {“name”: “名字”, “age”: 18}

下面這個函數可以用json序列化時間字段。

import json
from datetime import datetime,date

class CustomerJson(json.JSONEncoder):
    def default(self, o):
        if isinstance(o,datetime):
            return o.strftime('%Y-%m-%d %X')
        elif isinstance(o,date):
            return o.strftime('%Y-%m-%d')
        else:
            super().default(self,o)


res = {'c1':datetime.today(),'c2':date.today()}
print(json.dumps(res,cls=CustomerJson))

{“c1”: “2019-08-12 20:24:53”, “c2”: “2019-08-12”}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章