Python การใช้งาน JSON

JSON (JavaScript Object Notation) เป็นเครื่องมือสำคัญที่ใช้ในการจัดการข้อมูลในรูปแบบโครงสร้างข้อมูลที่สามารถแลกเปลี่ยนระหว่างระบบต่าง ๆ ได้อย่างมีประสิทธิภาพ โดยใน Python มีโมดูลชื่อว่า json ซึ่งใช้ในการแปลงข้อมูลระหว่าง JSON และโครงสร้างข้อมูลของ Python เช่น dict, list, และอื่น ๆ ได้ง่าย ๆ

ขั้นตอนการใช้งาน JSON ใน Python

การแปลง Python Object เป็น JSON (Serialization)

ฟังก์ชัน json.dumps() ใช้สำหรับแปลง Python object (เช่น dict หรือ list) ให้เป็นสตริงในรูปแบบ JSON

Python
import json

data = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

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

ผลลัพธ์

{"name": "John", "age": 30, "city": "New York"}

การแปลง JSON เป็น Python Object (Deserialization)

ฟังก์ชัน json.loads() ใช้ในการแปลง JSON string ให้กลับมาเป็น Python object

Python
json_data = '{"name": "John", "age": 30, "city": "New York"}'

# แปลง JSON string เป็น Python dict
data = json.loads(json_data)
print(data["name"])

ผลลัพธ์

การอ่าน/เขียน JSON จาก/ไปยังไฟล์

  • การเขียนข้อมูลในรูปแบบ JSON ลงไฟล์: ใช้ฟังก์ชัน json.dump()การอ่านข้อมูลจากไฟล์ที่อยู่ในรูปแบบ JSON: ใช้ฟังก์ชัน json.load()
  • Python
    # เขียนข้อมูล JSON ลงไฟล์
    with open('data.json', 'w') as json_file:
        json.dump(data, json_file)
    
    # อ่านข้อมูล JSON จากไฟล์
    with open('data.json', 'r') as json_file:
        data_from_file = json.load(json_file)
        print(data_from_file)

    การปรับแต่งการแสดงผล JSON

    เราสามารถใช้อาร์กิวเมนต์ indent เพื่อจัดการให้ JSON แสดงผลอย่างเป็นระเบียบ

    Python
    json_string_pretty = json.dumps(data, indent=4)
    print(json_string_pretty)

    ผลลัพธ์

    {
        "name": "John",
        "age": 30,
        "city": "New York"
    }

    การจัดการข้อมูลที่ซับซ้อน เช่น Custom Object

    หากต้องการแปลง Python object ที่ไม่ใช่ประเภทมาตรฐานเป็น JSON สามารถใช้การกำหนดวิธีการแปลงได้ด้วยการใช้ default parameter

    Python
    class Person:
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
    person = Person("Alice", 25)
    
    # ฟังก์ชันเพื่อแปลง Object เป็น dict
    def person_to_dict(obj):
        if isinstance(obj, Person):
            return {"name": obj.name, "age": obj.age}
        raise TypeError("Type not serializable")
    
    # แปลง Custom Object เป็น JSON
    json_string = json.dumps(person, default=person_to_dict)
    print(json_string)

    ผลลัพธ์

    {"name": "Alice", "age": 25}

    การจัดการ JSON ที่มีโครงสร้างซับซ้อน

    สามารถใช้ dumps() และ loads() เพื่อจัดการกับข้อมูลที่ซ้อนกัน เช่น list, dict ภายใน dict หรือ list ภายใน list

    Python
    complex_data = {
        "employees": [
            {"name": "John", "age": 30, "department": "HR"},
            {"name": "Anna", "age": 24, "department": "Tech"}
        ],
        "company": "ABC Corp"
    }
    
    # แปลงเป็น JSON
    json_string = json.dumps(complex_data, indent=4)
    print(json_string)
    
    # แปลงกลับมาเป็น Python Object
    python_data = json.loads(json_string)
    print(python_data["employees"][0]["name"])

    ผลลัพธ์

    {
        "employees": [
            {
                "name": "John",
                "age": 30,
                "department": "HR"
            },
            {
                "name": "Anna",
                "age": 24,
                "department": "Tech"
            }
        ],
        "company": "ABC Corp"
    }

    สรุป

    การใช้งาน JSON นั้นมีประโยชน์สำหรับการแลกเปลี่ยนข้อมูลระหว่างระบบหรือการเก็บข้อมูลในรูปแบบที่เข้าใจได้ง่ายทั้งสำหรับมนุษย์และเครื่อง นอกจากการแปลง Python object เป็น JSON string และกลับกันแล้ว ยังสามารถใช้งานร่วมกับไฟล์ได้อย่างสะดวก

    แชร์เรื่องนี้