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

Python JSON Parsing: คู่มือ json.load, json.loads และ Data Extraction

JSON (JavaScript Object Notation) เป็นรูปแบบข้อมูลมาตรฐาน Python มีโมดูล json Built-in สำหรับ Parse และ Serialize

JSON ตัวอย่าง (store.json)

{
  "store": {
    "book": [
      {
        "category": "reference",
        "author": "Nigel Rees",
        "title": "Sayings of the Century",
        "price": 8.95
      },
      {
        "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": 12.99
      }
    ],
    "bicycle": {
      "color": "red",
      "price": 19.95
    }
  },
  "expensive": 10
}

1. Parse JSON File: json.load()

import json

with open('store.json', 'r', encoding='utf-8') as f:
    data = json.load(f)

print(type(data))  # 
print(data)

💡 Key Point: json.load() คืนค่า Python Dictionary (สำหรับ JSON Object) หรือ List (สำหรับ JSON Array)

2. Parse JSON String: json.loads()

import json

json_string = '{"name": "John", "age": 30}'
data = json.loads(json_string)
print(data['name'])  # John

3. ดึงข้อมูลจาก Parsed Data (Dictionary Methods)

# ดึงค่า Nested Object
bicycle_price = data['store']['bicycle']['price']
print(bicycle_price)  # 19.95

# ดึงค่าจาก Array (ใช้ Index)
second_book_title = data['store']['book'][1]['title']
print(second_book_title)  # Sword of Honour

# Safe access with .get() - ไม่โยน KeyError
price = data.get('store', {}).get('bicycle', {}).get('price')
# หรือ Python 3.8+ walrus operator
if (store := data.get('store')) and (bicycle := store.get('bicycle')):
    print(bicycle.get('price'))

4. Conditional Parsing (Filter ข้อมูล)

# หาหนังสือที่ราคา <= 10.00
books = data['store']['book']
affordable_books = [book for book in books if book['price'] <= 10.00]

for book in affordable_books:
    print(f"{book['title']} by {book['author']} - ${book['price']}")

# Output:
# Sayings of the Century by Nigel Rees - $8.95

5. Serialize Python → JSON: json.dump() / json.dumps()

import json

data = {
    "name": "John",
    "age": 30,
    "skills": ["Python", "Java", "SQL"]
}

# เขียนไฟล์
with open('output.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, indent=2, ensure_ascii=False)

# แปลงเป็น String
json_str = json.dumps(data, indent=2, ensure_ascii=False)
print(json_str)

Output:

{
  "name": "John",
  "age": 30,
  "skills": [
    "Python",
    "Java",
    "SQL"
  ]
}

6. Custom JSON Encoder (สำหรับ Object ที่ไม่รองรับ)

import json
from datetime import datetime

class CustomEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.isoformat()
        return super().default(obj)

data = {"created": datetime.now()}
json_str = json.dumps(data, cls=CustomEncoder)
# {"created": "2024-01-15T14:30:45.123456"}

Common Errors และการแก้ไข

Errorสาเหตุแก้ไข
JSONDecodeErrorJSON Format ผิด (comma, quote, bracket)Validate JSON ก่อน Parse
KeyErrorKey ไม่มีใน Dictใช้ .get() หรือ try/except
TypeError: not serializableObject ไม่สามารถแปลง JSON ได้ (datetime, set, custom class)ใช้ Custom Encoder หรือแปลงก่อน
UnicodeEncodeErrorThai/Unicode charactersใช้ ensure_ascii=False และ encoding='utf-8'

บทความเกี่ยวข้อง