Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Làm sao để class Python có thể serialize JSON?

Serialisation là chuyển đổi đối tượng phức tạp thành kiểu dữ liệu gốc (dict, list, str, int, float, bool, None) để dễ dàng xuất JSON.

json.dumps() - Chuyển dict/list thành JSON string

import json

x = {
    "name": "Archana",
    "age": 30,
    "city": "Hyderabad"
}
y = json.dumps(x)
print(y)
{"name": "Archana", "age": 30, "city": "Hyderabad"}

Ví dụ với dict key số (tự chuyển thành string)

import json

Emp = {1: "Archana", 2: "Krishna", 3: "Vineeth", 4: "Ramesh"}
jsonString = json.dumps(Emp)
print(jsonString)

Empid = [71, 72, 73, 74]
jsonString = json.dumps(Empid)
print(jsonString)
{"1": "Archana", "2": "Krishna", "3": "Vineeth", "4": "Ramesh"}
[71, 72, 73, 74]

Tùy chỉnh serialize cho class riêng

Mặc định json.dumps() không hỗ trợ object tùy chỉnh. Có 2 cách:

Cách 1: Triển khai phương thức to_dict()

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def to_dict(self):
        return {"name": self.name, "age": self.age}

p = Person("An", 25)
print(json.dumps(p.to_dict()))

Cách 2: Dùng default parameter trong json.dumps()

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

def person_encoder(obj):
    if isinstance(obj, Person):
        return {"name": obj.name, "age": obj.age}
    raise TypeError(f"Object of type {type(obj)} not serializable")

p = Person("Bình", 30)
print(json.dumps(p, default=person_encoder))

Cách 3: Kế thừa json.JSONEncoder

class PersonEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Person):
            return {"name": obj.name, "age": obj.age}
        return super().default(obj)

print(json.dumps(p, cls=PersonEncoder))

Pickle - Serialize đối tượng Python nhị phân

Module pickle serialize bất kỳ object Python nào (kể cả function, class) thành byte stream:

import pickle

data = {"key": "value", "num": 42}
pickled = pickle.dumps(data)
unpickled = pickle.loads(pickled)
print(unpickled)

Cảnh báo: Pickle không an toàn với dữ liệu không tin cậy (có thể thực thi code tùy ý). Chỉ dùng JSON cho dữ liệu trao đổi.