Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีทำให้ Class รองรับ JSON Serialization ใน Python

Serialization (อนุกรม化) คือกระบวนการแปลงวัตถุชนิดข้อมูลซับซ้อนให้เป็นชนิดข้อมูลพื้นฐาน (native data types) เพื่อให้สามารถแปลงเป็น JSON Notation ได้ง่ายขึ้น

หากคุณมีออบเจกต์ Python คุณสามารถแปลงเป็น JSON String โดยใช้เมธอด json.dumps()

โมดูล pickle ใน Python ใช้สำหรับ Serialize และ Deserialize โครงสร้างออบเจกต์ Python วัตถุใดๆ ใน Python สามารถ Pickled ได้เพื่อบันทึกบนดิสก์ Pickle จะ "serialize" ออบเจกต์ก่อนเขียนลงไฟล์ Pickling เป็นวิธีแปลงออบเจกต์ Python (list, dict, ฯลฯ) ให้เป็นสตรีมอักขระ

ตัวอย่างที่ 1: แปลง Dictionary เป็น JSON

import json

data = {
    "name": "Archana",
    "age": 30,
    "city": "Hyderabad"
}

# แปลงเป็น JSON String
json_string = json.dumps(data)
print(json_string)

ผลลัพธ์

{"name": "Archana", "age": 30, "city": "Hyderabad"}

ตัวอย่างที่ 2: แปลง Dictionary และ List เป็น JSON

import json

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

emp_id = [71, 72, 73, 74]
json_string = json.dumps(emp_id)
print(json_string)

ผลลัพธ์

{"1": "Archana", "2": "Krishna", "3": "Vineeth", "4": "Ramesh"}
[71, 72, 73, 74]

ทำให้ Custom Class รองรับ JSON

หากต้องการให้ Class ของตัวเอง Serialize เป็น JSON ได้ ให้เพิ่มเมธอด to_dict() หรือใช้ default parameter ใน json.dumps()

import json

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("John", 25)
json_str = json.dumps(p.to_dict())
print(json_str)