Tag: JSON

  • วิธีใช้ jsonlite เพื่อทำงานกับ JSON ในภาษา R: fromJSON(), toJSON(), read_json(), และ write_json() — ตัวอย่างการทำงานกับข้อมูลขนม

    วิธีใช้ jsonlite เพื่อทำงานกับ JSON ในภาษา R: fromJSON(), toJSON(), read_json(), และ write_json() — ตัวอย่างการทำงานกับข้อมูลขนม

    ในบทความนี้ เราจะไปดูวิธีการใช้ 4 functions จาก jsonlite package สำหรับทำงานกับ JSON (JavaScript Object Notation) ในภาษา R กัน:

    1. fromJSON()
    2. toJSON()
    3. read_json()
    4. write_json()

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


    1. 🤔 What Is JSON?
    2. 📦 What Is jsonlite?
    3. 🏁 Getting Started
    4. ⬇️ Function 1. fromJSON()
    5. ⬆️ Function 2. toJSON()
    6. 📖 Function 3. read_json()
    7. ✍️ Function 4. write_json()
    8. 💪 Summary
    9. 😺 GitHub
    10. 📃 References

    🤔 What Is JSON?

    JSON เป็นโครงสร้างข้อมูลที่พบได้บ่อยในระบบคอมพิวเตอร์และแอปพลิเคชันต่าง ๆ เพราะเป็นรูปแบบข้อมูลที่อ่านได้ง่ายทั้งคนและคอมพิวเตอร์

    ตัวอย่าง JSON ที่เก็บข้อมูลขนม:

    [
      {
        "snack_name": "Corn Chips",
        "brand": "Nibble & Dip",
        "price_usd": 2.99,
        "is_vegan": true
      },
      {
        "snack_name": "Pita Chips",
        "brand": "DipMates",
        "price_usd": 4.25,
        "is_vegan": false
      },
      {
        "snack_name": "Tortilla Chips",
        "brand": "Casa Crunch",
        "price_usd": 3.49,
        "is_vegan": true
      }
    ]
    

    Note: อ่านเพิ่มเติมเกี่ยวกับ JSON ได้ที่ What is JSON?


    📦 What Is jsonlite?

    jsonlite เป็น package ขนาดเบาสำหรับทำงานกับ JSON ในภาษา R และมี 4 functions หลักให้เรียกใช้งาน ได้แก่:

    1. fromJSON(): โหลด JSON string (character ที่มีข้อมูลแบบ JSON) เป็น R object (เช่น data frame)
    2. toJSON(): เปลี่ยน R object เป็น JSON string
    3. read_json(): โหลดไฟล์ JSON เป็น R object
    4. write_json(): เปลี่ยน R object เป็นไฟล์ JSON

    เราไปดูวิธีใช้ jsonlite และ 4 functions นี้กัน


    🏁 Getting Started

    ก่อนเริ่มใช้งาน jsonlite เราจะต้องทำ 2 อย่าง ได้แก่:

    1. ติดตั้ง package ด้วย install.packages() (ทำครั้งแรกครั้งเดียว)
    2. โหลด package ด้วย library() (ทำทุกครั้งที่เปิด session ใหม่)
    # Install jsonlite
    install.packages("jsonlite")
    
    # Load jsonlite
    library(jsonlite)
    

    ⬇️ Function 1. fromJSON()

    fromJSON() ใช้เปลี่ยน JSON ที่เป็นอยู่ใน character (JSON string) ให้เป็น R object เช่น list และ data frame

    เช่น เราสามารถเปลี่ยน JSON string แบบนี้:

    # Create a JSON string
    snacks_json_string <- '
    [
      {
        "snack_name": "Corn Chips",
        "brand": "Nibble & Dip",
        "price_usd": 2.99,
        "is_vegan": true
      },
      {
        "snack_name": "Pita Chips",
        "brand": "DipMates",
        "price_usd": 4.25,
        "is_vegan": false
      },
      {
        "snack_name": "Tortilla Chips",
        "brand": "Casa Crunch",
        "price_usd": 3.49,
        "is_vegan": true
      }
    ]
    '
    
    

    ให้เป็น R object ได้แบบนี้:

    # Convert to R object
    snacks_r_obj <- fromJSON(snacks_json_string)
    
    # View the df
    snacks_r_obj
    

    ผลลัพธ์:

          snack_name        brand price_usd is_vegan
    1     Corn Chips Nibble & Dip      2.99     TRUE
    2     Pita Chips     DipMates      4.25    FALSE
    3 Tortilla Chips  Casa Crunch      3.49     TRUE
    

    Note: fromJSON() จะเลือกประเภท R object ให้โดยอัตโนมัติ เช่น ถ้า JSON มีโครงสร้างคล้าย data frame (มีข้อมูลซ้ำ ๆ ที่ดูเหมือน rows และ columns) fromJSON() จะเปลี่ยน JSON string ให้เป็น data frame


    ⬆️ Function 2. toJSON()

    toJSON() ใช้เปลี่ยน R object ให้เป็น JSON string

    เช่น เปลี่ยน data frame นี้:

    # Create a data frame
    snacks_df <- data.frame(
      snack_name = c("Seaweed Thins", "Chickpea Puffs", "BBQ Potato Crisps"),
      brand      = c("OceanBite", "LegumeLab", "Spud & Spark"),
      price_usd  = c(2.45, 3.35, 3.10),
      is_vegan   = c(TRUE, TRUE, FALSE),
      stringsAsFactors = FALSE
    )
    

    ให้เป็น JSON string:

    # Convert to JSON string
    snacks_json_string <- toJSON(snacks_df)
    
    # View the JSON string
    snacks_json_string
    

    ผลลัพธ์:

    [{"snack_name":"Seaweed Thins","brand":"OceanBite","price_usd":2.45,"is_vegan":true},{"snack_name":"Chickpea Puffs","brand":"LegumeLab","price_usd":3.35,"is_vegan":true},{"snack_name":"BBQ Potato Crisps","brand":"Spud & Spark","price_usd":3.1,"is_vegan":false}]
    

    สังเกตว่า ผลลัพธ์ที่ได้มาอ่านยาก เพราะข้อมูลอยู่ในบรรทัดเดียวกันหมด

    ทั้งนี้ เราเปลี่ยนให้ผลลัพธ์อ่านง่ายขึ้นได้ โดยใช้ pretty argument แบบนี้:

    # Convert to JSON string (pretty)
    snacks_json_string_pretty <- toJSON(snacks_df,
    pretty = TRUE)
    # View the JSON string (pretty)
    snacks_json_string_pretty

    ผลลัพธ์:

    [
      {
        "snack_name": "Seaweed Thins",
        "brand": "OceanBite",
        "price_usd": 2.45,
        "is_vegan": true
      },
      {
        "snack_name": "Chickpea Puffs",
        "brand": "LegumeLab",
        "price_usd": 3.35,
        "is_vegan": true
      },
      {
        "snack_name": "BBQ Potato Crisps",
        "brand": "Spud & Spark",
        "price_usd": 3.1,
        "is_vegan": false
      }
    ]
    

    จะเห็นว่า ตอนนี้ JSON string อ่านง่ายกว่าก่อนหน้านี้มาก


    📖 Function 3. read_json()

    read_json() ใช้โหลดไฟล์ JSON เข้ามาใน R

    เช่น เรามีไฟล์ชื่อ snacks.json ที่มีข้อมูลแบบนี้:

    [
      {
        "snack_name": "Plantain Chips",
        "brand": "TropiBite",
        "price_usd": 3.15,
        "is_vegan": true
      },
      {
        "snack_name": "Rice Crackers",
        "brand": "ZenMunch",
        "price_usd": 2.25,
        "is_vegan": true
      },
      {
        "snack_name": "Pretzel Sticks",
        "brand": "Twist & Dip",
        "price_usd": 3.75,
        "is_vegan": true
      }
    ]
    

    เราสามารถโหลดเข้ามาใน R ด้วย read_json() ได้แบบนี้:

    # Read the JSON file
    snacks_from_json_file <- read_json("snacks.json")
    
    # View the result
    snacks_from_json_file
    

    ผลลัพธ์:

    [[1]]
    [[1]]$snack_name
    [1] "Plantain Chips"
    
    [[1]]$brand
    [1] "TropiBite"
    
    [[1]]$price_usd
    [1] 3.15
    
    [[1]]$is_vegan
    [1] TRUE
    
    [[2]]
    [[2]]$snack_name
    [1] "Rice Crackers"
    
    [[2]]$brand
    [1] "ZenMunch"
    
    [[2]]$price_usd
    [1] 2.25
    
    [[2]]$is_vegan
    [1] TRUE
    
    [[3]]
    [[3]]$snack_name
    [1] "Pretzel Sticks"
    
    [[3]]$brand
    [1] "Twist & Dip"
    
    [[3]]$price_usd
    [1] 3.75
    
    [[3]]$is_vegan
    [1] TRUE
    

    ทั้งนี้ read_json() มี simplifyVector argument ที่ช่วยโหลดข้อมูลที่เหมือน data frame ให้เป็น data frame (แทน list) ได้แบบนี้:

    # Read the JSON file (simplified)
    snacks_from_json_file_simplified <- read_json("snacks.json",
                                                  simplifyVector = TRUE)
    
    # View the result (simplified)
    snacks_from_json_file_simplified
    

    ผลลัพธ์:

          snack_name       brand price_usd is_vegan
    1 Plantain Chips   TropiBite      3.15     TRUE
    2  Rice Crackers    ZenMunch      2.25     TRUE
    3 Pretzel Sticks Twist & Dip      3.75     TRUE
    

    ✍️ Function 4. write_json()

    write_json() ใช้เปลี่ยน R object ให้เป็นไฟล์ JSON

    เช่น เปลี่ยน data frame นี้:

    # Create a list
    snacks_df <- data.frame(
      snack_name = c("Cassava Chips", "Lentil Crisps", "Cheese Puffs"),
      brand      = c("RootRush", "Pulse & Crunch", "CheezyPop"),
      price_usd  = c(2.85, 2.65, 3.99),
      is_vegan   = c(TRUE, TRUE, FALSE),
      stringsAsFactors = FALSE
    )
    

    ให้เป็นไฟล์ JSON แบบนี้:

    # Write to JSON
    write_json(snacks_df,
               "snacks_df.json")
    

    ผลลัพธ์:

    [{"snack_name":"Cassava Chips","brand":"RootRush","price_usd":2.85,"is_vegan":true},{"snack_name":"Lentil Crisps","brand":"Pulse & Crunch","price_usd":2.65,"is_vegan":true},{"snack_name":"Cheese Puffs","brand":"CheezyPop","price_usd":3.99,"is_vegan":false}]
    

    เช่นเดียวกับ toJSON(), write_json() มี pretty argument ที่ทำให้ผลลัพธ์อ่านง่ายขึ้นได้:

    # Write to JSON (pretty)
    write_json(snacks_df,
               "snacks_df_pretty.json", 
               pretty = TRUE)
    

    ผลลัพธ์:

    [
      {
        "snack_name": "Cassava Chips",
        "brand": "RootRush",
        "price_usd": 2.85,
        "is_vegan": true
      },
      {
        "snack_name": "Lentil Crisps",
        "brand": "Pulse & Crunch",
        "price_usd": 2.65,
        "is_vegan": true
      },
      {
        "snack_name": "Cheese Puffs",
        "brand": "CheezyPop",
        "price_usd": 3.99,
        "is_vegan": false
      }
    ]
    

    💪 Summary

    ในบทความนี้ เราได้ไปทำความรู้จักกับ 4 functions จาก jsonlite ซึ่งเป็น package สำหรับทำงานกับ JSON ในภาษา R:

    1. fromJSON(): JSON string → R object
    2. toJSON(): R object → JSON string
    3. read_json(): ไฟล์ JSON → R object
    4. write_json(): R object → JSON

    😺 GitHub

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


    📃 References

  • แนะนำ 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