Python ทำงานกับ JSON



JSON (JavaScript Object Notation) เป็นรูปแบบข้อความสำหรับเก็บข้อมูลที่มีโครงสร้าง เกือบทุก API บนอินเทอร์เน็ตรับส่งข้อมูลเป็น JSON และไฟล์ตั้งค่าจำนวนมากก็เป็น JSON โครงสร้างของมันแทบจะตรงกับ dict และ list ของ Python พอดี

JSON ตัวอย่าง

{
  "name": "สมชาย",
  "age": 25,
  "active": true,
  "skills": ["Python", "SQL"],
  "address": {
    "city": "กรุงเทพ",
    "zip": "10100"
  }
}

JSON ↔ Python จับคู่กันยังไง

JSONPython
object {}dict
array []list
stringstr
numberint / float
true / falseTrue / False
nullNone

แปลง Python เป็น JSON

json.dumps() — dump to string

import json

data = {
    "name": "สมชาย",
    "age": 25,
    "skills": ["Python", "SQL"],
}

text = json.dumps(data)
print(text)
# {"name": "สมชาย", "age": 25, "skills": ["Python", "SQL"]}

ภาษาไทยกลายเป็น \uXXXX ให้ใส่ ensure_ascii=False และจัดย่อหน้าด้วย indent

text = json.dumps(data, ensure_ascii=False, indent=2)
print(text)
{
  "name": "สมชาย",
  "age": 25,
  "skills": [
    "Python",
    "SQL"
  ]
}

แปลง JSON เป็น Python

json.loads() — load from string

import json

text = '{"name": "สมหญิง", "age": 30, "active": true}'
data = json.loads(text)

print(data["name"])     # สมหญิง
print(data["active"])   # True  (ไม่ใช่ true)
print(type(data))       # <class 'dict'>

อ่าน/เขียนไฟล์ JSON

dump / load (ไม่มี s) ทำงานกับไฟล์โดยตรง

เขียนลงไฟล์

import json

config = {
    "theme": "dark",
    "language": "th",
    "notifications": True,
}

with open("config.json", "w", encoding="utf-8") as f:
    json.dump(config, f, ensure_ascii=False, indent=2)

อ่านจากไฟล์

import json

with open("config.json", "r", encoding="utf-8") as f:
    config = json.load(f)

print(config["theme"])   # dark

จัดการไฟล์เสียหรือไม่มีอยู่

import json

def load_config(path):
    try:
        with open(path, "r", encoding="utf-8") as f:
            return json.load(f)
    except FileNotFoundError:
        print("ไม่พบไฟล์ ใช้ค่าเริ่มต้น")
        return {}
    except json.JSONDecodeError as e:
        print(f"ไฟล์ JSON เสีย: {e}")
        return {}

config = load_config("config.json")

JSON กับข้อมูลจาก API

ไลบรารี requests แปลง JSON ให้อัตโนมัติผ่านเมท็อด .json()

import requests

response = requests.get("https://api.github.com/users/python")
data = response.json()          # เป็น dict แล้ว

print(data["name"])             # Python
print(data["public_repos"])

สิ่งที่ JSON เก็บไม่ได้

json.dumps() จะ error ถ้าเจอชนิดที่ JSON ไม่รู้จัก เช่น datetime, set, ทูเพิลจะกลายเป็น array

import json
from datetime import datetime

json.dumps({"time": datetime.now()})   # TypeError

ทางแก้: แปลงเป็น string ก่อน หรือใช้พารามิเตอร์ default

data = {"time": datetime.now()}
text = json.dumps(data, default=str)   # แปลงสิ่งที่ไม่รู้จักด้วย str()

ตัวอย่างรวม: ระบบเก็บรายชื่อติดต่อ

import json
from pathlib import Path

FILE = Path("contacts.json")


def load():
    if FILE.exists():
        with open(FILE, "r", encoding="utf-8") as f:
            return json.load(f)
    return []


def save(contacts):
    with open(FILE, "w", encoding="utf-8") as f:
        json.dump(contacts, f, ensure_ascii=False, indent=2)


contacts = load()

while True:
    choice = input("\n1) เพิ่ม  2) แสดง  0) ออก : ")

    if choice == "1":
        name = input("ชื่อ: ")
        phone = input("เบอร์: ")
        contacts.append({"name": name, "phone": phone})
        save(contacts)
        print("บันทึกแล้ว")

    elif choice == "2":
        for c in contacts:
            print(f"  {c['name']} — {c['phone']}")

    elif choice == "0":
        break

ข้อมูลถูกเก็บเป็นไฟล์ contacts.json ที่เปิดอ่านด้วยตาได้ และโปรแกรมอื่นก็เอาไปใช้ต่อได้

เช็คความเข้าใจก่อนข้ามบท

  • แปลง dict/list ของ Python เป็น JSON และแปลงกลับได้
  • อ่านและเขียนไฟล์ JSON โดยใช้ json.load() และ json.dump() ได้
  • บอกได้ว่าข้อมูลชนิดใดเก็บใน JSON โดยตรงไม่ได้

สรุป

  • dumps/loads ทำงานกับ string, dump/load ทำงานกับไฟล์
  • ใส่ ensure_ascii=False เพื่อให้ภาษาไทยไม่กลายเป็น \uXXXX, indent=2 เพื่อจัดย่อหน้า
  • JSON object → dict, array → list, true/false/null → True/False/None
  • ดัก json.JSONDecodeError เมื่อไฟล์อาจเสีย

จบช่วงเรื่องไฟล์ บทถัดไปเริ่มการเขียนโปรแกรมเชิงวัตถุ (OOP) ด้วยคลาสและอ็อบเจกต์