天天看点

Python编程:json序列化python对象

相关:  Python编程:json模块和pickle模块

# -*- coding: utf-8 -*-

# @File    : json_demo.py
# @Date    : 2018-06-04
# @Author  : Peng Shiyu

# 定制序列化或反序列化的规则
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)
    # {"name": "Tom", "age": 23}

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

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