Tag: JSNO

  • แนะนำ 4 functions ในการทำงานกับ JSON ใน Python: json.dumps(), json.loads(), json.dump(), และ json.load() — ตัวอย่างการทำงานกับข้อมูลคำสั่งซื้อคุกกี้

    แนะนำ 4 functions ในการทำงานกับ JSON ใน Python: json.dumps(), json.loads(), json.dump(), และ json.load() — ตัวอย่างการทำงานกับข้อมูลคำสั่งซื้อคุกกี้

    ในบทความนี้ เราจะไปดูวิธีใช้ 4 functions จาก json package ใน Python สำหรับทำงานกับ JSON (JavaScript Object Notation) ซึ่งเป็น data structure ที่พบได้บ่อยในแอปพลิเคชันและระบบต่าง ๆ กัน:

    1. json.loads()
    2. json.dumps()
    3. json.load()
    4. json.dump()

    ตัวอย่าง JSON คำสั่งซื้อออนไลน์:

    {
      "order_id": 1024,
      "customer": {
        "name": "Ari Lee",
        "phone": "+66 89 123 4567"
      },
      "items": [
        {
          "product": "Cappuccino",
          "size": "Medium",
          "price": 75,
          "quantity": 1
        },
        {
          "product": "Ham Sandwich",
          "price": 95,
          "quantity": 2
        }
      ],
      "payment": {
        "method": "QR Code",
        "total": 170,
        "currency": "THB"
      },
      "status": "Preparing",
      "timestamp": "2025-10-11T09:30:00"
    }
    

    ถ้าพร้อมแล้ว ไปเริ่มกันเลย


    1. 🏁 Introduction to json
    2. 🗨️ Group 1. JSON Strings
      1. ⬇️ json.loads(): JSON String to Python Object
      2. ⬆️ json.dumps(): Python Object to JSON String
    3. 📂 Group 2. JSON Files
      1. ⬇️ json.load(): JSON File to Python Object
      2. ⬆️ json.dump(): Python Object to JSON File
    4. 💪 Summary
    5. 😺 GitHub
    6. 📃 References

    🏁 Introduction to json

    json เป็น built-in package ใน Python และถูกออกแบบมาสำหรับทำงานกับ JSON โดยเฉพาะ

    เราสามารถเริ่มใช้งาน json ด้วยการโหลด package ด้วย import:

    # Import json
    import json
    

    json มี 4 functions สำหรับทำงานกับ JSON ซึ่งแบ่งได้เป็น 2 กลุ่ม:

    1. ทำงานกับ JSON string หรือ JSON ที่อยู่ในรูป Python string:
      1. json.loads()
      2. json.dumps()
    2. ทำงานกับ JSON file หรือ file ที่เห็นข้อมูล JSON เอาไว้:
      1. json.load()
      2. json.dump()

    Note: เทคนิคการจำ คือ function ที่ลงท้ายด้วย s (เช่น json.loads()) แสดงว่าใช้งานกับ JSON string

    ทั้ง 4 functions มีรายละเอียดการใช้งาน ดังนี้:

    FunctionFromTo
    json.loads()JSON string 🗨️Python object 🐍
    json.dumps()Python object 🐍JSON string 🗨️
    json.load()JSON file 📂Python object 🐍
    json.dump()Python object 🐍JSON file 📂

    เราไปดูวิธีใช้งานทั้ง 4 functions กับตัวอย่างข้อมูลสั่งซื้อคุกกี้กัน


    🗨️ Group 1. JSON Strings

    2 functions สำหรับทำงานกับ JSON string หรือ JSON ที่อยู่ในรูปของ Python string ได้แก่:

    FunctionFromTo
    json.loads()JSON string 🗨️Python object 🐍
    json.dumps()Python object 🐍JSON string 🗨️

    .

    ⬇️ json.loads(): JSON String to Python Object

    json.loads() ใช้โหลด JSON string ให้เป็น Python object เช่น:

    • String: ""
    • List: []
    • Dictionary: {}

    ยกตัวอย่างเช่น:

    # Create a Python dict
    cookie_json_string = """
    {
        "customer": "May",
        "cookies": [
            "Chocolate Chip",
            "Oatmeal",
            "Sugar"
        ],
        "is_member": true,
        "total_price": 120
    }
    """
    
    # Convert to Python object
    cookie_python_dict = json.loads(cookie_json_string)
    

    เราสามารถดูผลลัพธ์ได้ด้วย pprint() ซึ่งเป็น function สำหรับ print Python dictionary ให้อ่านง่าย:

    # Import pprint
    from pprint import pprint
    
    # View the result
    pprint(cookie_python_dict)
    

    ผลลัพธ์:

    {'cookies': ['Chocolate Chip', 'Oatmeal', 'Sugar'],
     'customer': 'May',
     'is_member': True,
     'total_price': 120}
    

    .

    ⬆️ json.dumps(): Python Object to JSON String

    ในกรณีที่เรามี Python object เราสามารถแปลงเป็น JSON string ได้ด้วย json.dumps():

    # Create a Python dict
    cookie_py_dict = {
        "customer": "May",
        "cookies": [
            "Chocolate Chip",
            "Oatmeal",
            "Sugar"
        ],
        "is_member": True,
        "total_price": 120
    }
    
    # Convert to JSON string
    cookie_json_str = json.dumps(cookie_py_dict)
    
    # View the result
    print(cookie_json_str)
    

    ผลลัพธ์:

    {"customer": "May", "cookies": ["Chocolate Chip", "Oatmeal", "Sugar"], "is_member": true, "total_price": 120}
    

    ทั้งนี้ เราสามารถใช้ indent เพื่อทำให้ JSON string อ่านง่ายขึ้นได้ เช่น:

    # Convert to JSON string with indent argument
    cookie_json_str_indent = json.dumps(cookie_py_dict, indent=4)
    
    # View the result
    print(cookie_json_str_indent)
    

    ผลลัพธ์:

    {
        "customer": "May",
        "cookies": [
            "Chocolate Chip",
            "Oatmeal",
            "Sugar"
        ],
        "is_member": true,
        "total_price": 120
    }
    

    📂 Group 2. JSON Files

    เรามี 2 functions สำหรับทำงานกับ JSON files ได้แก่:

    FunctionFromTo
    json.load()JSON file 📂Python object 🐍
    json.dump()Python object 🐍JSON file 📂

    .

    ⬇️ json.load(): JSON File to Python Object

    json.load() ใช้สำหรับโหลดข้อมูลจาก JSON file เข้ามาใน Python

    เช่น เรามี JSON file ดังนี้:

    {
        "order_id": 2048,
        "customer": {
            "name": "MJ",
            "phone": "+66 92 888 4321"
        },
        "items": [
            {
                "product": "Double Chocolate Cookie",
                "size": "Large",
                "price": 55,
                "quantity": 2
            },
            {
                "product": "Almond Biscotti",
                "price": 45,
                "quantity": 3
            }
        ],
        "payment": {
            "method": "Credit Card",
            "total": 285,
            "currency": "THB"
        },
        "status": "Baking",
        "timestamp": "2025-10-11T10:15:00"
    }
    

    เราสามารถโหลดขัอมูลได้แบบนี้:

    # Load JSON data
    with open("cookie_order.json", "r") as file:
        cookie_order = json.load(file)
    
    # View the result
    pprint(cookie_order)
    

    ผลลัพธ์:

    {'customer': {'name': 'MJ', 'phone': '+66 92 888 4321'},
     'items': [{'price': 55,
                'product': 'Double Chocolate Cookie',
                'quantity': 2,
                'size': 'Large'},
               {'price': 45, 'product': 'Almond Biscotti', 'quantity': 3}],
     'order_id': 2048,
     'payment': {'currency': 'THB', 'method': 'Credit Card', 'total': 285},
     'status': 'Baking',
     'timestamp': '2025-10-11T10:15:00'}
    

    .

    ⬆️ json.dump(): Python Object to JSON File

    json.dump() ใช้สร้าง JSON file จาก Python objects

    เช่น update ข้อมูลผู้ซื้อใน cookie_order จาก "MJ" เป็น "Peter Parker" และสร้างเป็น JSON file:

    # Update name
    cookie_order["customer"]["name"] = "Peter Parker"
    
    # Write to JSON file
    with open("cookie_order_updated.json", "w") as file:
        json.dump(cookie_order, file, indent=2)
    

    Note: สังเกตว่า เราสามารถกำหนด indent เพื่อทำให้ JSON อ่านง่ายขึ้นได้เหมือนกับ json.dumps()

    ผลลัพธ์ใน JSON file:

    {
      "order_id": 2048,
      "customer": {
        "name": "Peter Parker",
        "phone": "+66 92 888 4321"
      },
      "items": [
        {
          "product": "Double Chocolate Cookie",
          "size": "Large",
          "price": 55,
          "quantity": 2
        },
        {
          "product": "Almond Biscotti",
          "price": 45,
          "quantity": 3
        }
      ],
      "payment": {
        "method": "Credit Card",
        "total": 285,
        "currency": "THB"
      },
      "status": "Baking",
      "timestamp": "2025-10-11T10:15:00"
    }
    

    💪 Summary

    ในบทความนี้ เราได้ไปดูวิธีการใช้ 4 functions จาก json package เพื่อทำงานกับ JSON ใน Python:

    FunctionFromTo
    json.loads()JSON string 🗨️Python object 🐍
    json.dumps()Python object 🐍JSON string 🗨️
    json.load()JSON file 📂Python object 🐍
    json.dump()Python object 🐍JSON file 📂

    Note: json.dumps() และ json.dump() มี indent argument ที่ทำให้ JSON ออกอ่านง่ายได้


    😺 GitHub

    ดูตัวอย่าง code และ file ในบทความนี้ได้ที่ GitHub


    📃 References