教學

Python 處理 JSON 實戰指南:讀取、寫入、驗證與轉換

使用 Python 標準函式庫安全處理 JSON,涵蓋檔案讀寫、錯誤定位、數字精度、資料轉換、命令列檢查與正式環境注意事項。

2026-07-2911 分鐘

Python 內建的 json 模組足以處理大多數日常工作。真正容易出錯的地方通常是編碼、例外、數字精度與資料結構變動。

解析文字並保留錯誤位置

import json

raw = '{"name": "Ada", "active": true}'

try:
    data = json.loads(raw)
except json.JSONDecodeError as exc:
    print(f"JSON 無效:第 {exc.lineno} 行,第 {exc.colno} 欄:{exc.msg}")
    raise

日誌應記錄行列與請求 ID,不要寫入含有密鑰或個資的完整內容。正式匯入也不應悄悄修復輸入後繼續執行。

使用 UTF-8 讀寫檔案

import json
from pathlib import Path

source = Path("input.json")
target = Path("output.json")

with source.open("r", encoding="utf-8") as handle:
    data = json.load(handle)

with target.open("w", encoding="utf-8") as handle:
    json.dump(data, handle, ensure_ascii=False, indent=2)
    handle.write("\n")

寫入重要設定時,可先寫暫存檔,成功後再取代正式檔案,避免程式中斷留下不完整 JSON。

必要時保留十進位精度

import json
from decimal import Decimal

payload = json.loads('{"amount": 19.99}', parse_float=Decimal)
print(payload["amount"] * 3)

Decimal 預設不能直接序列化。請先決定外部契約使用十進位字串,或使用最小貨幣單位整數,再明確轉換。

轉換前驗證結構

def normalize_users(value):
    if not isinstance(value, list):
        raise ValueError("根節點必須是陣列")

    result = []
    for index, item in enumerate(value):
        if not isinstance(item, dict):
            raise ValueError(f"第 {index} 項必須是物件")
        if "id" not in item or "email" not in item:
            raise ValueError(f"第 {index} 項缺少 id 或 email")
        result.append({
            "id": str(item["id"]),
            "email": str(item["email"]).strip().lower(),
        })
    return result

複雜契約可搭配 JSON Schema 與維護良好的驗證函式庫。語法正確不代表資料符合業務契約。

轉換時保留語意

將巢狀 JSON 轉成 CSV 或資料庫資料列之前,要先定義陣列、缺少欄位、null 與巢狀物件的表示方式。

def order_row(order):
    customer = order.get("customer") or {}
    return {
        "order_id": order.get("id"),
        "customer_email": customer.get("email"),
        "item_count": len(order.get("items") or []),
        "status": order.get("status", "unknown"),
    }

為輸入與輸出保留測試樣本,讓每項轉換決策都能被檢查。

使用命令列快速檢查

python -m json.tool input.json
python -m json.tool --sort-keys input.json

需要快速檢視時,可使用 JSON 美化器JSON 樹狀檢視器。任何工具都不應接收不必要的密鑰或個資。

上線前清單

  • • 明確指定 UTF-8。
  • • 限制輸入大小與巢狀深度。
  • • 區分缺少欄位與明確 null
  • • 精度敏感資料使用 Decimal、字串或最小單位整數。
  • • 轉換之前先驗證結構。
  • • 測試空陣列、Unicode、大整數與不完整紀錄。

Python 官方 json 模組文件列出完整選項。先使用標準函式庫,在契約需要時加入 Schema 驗證,並讓轉換規則保持明確可稽核。

Ene Chen

致力於為開發者提供最佳的 JSON 處理工具

相關文章

更多文章即將發布...

返回部落格

相關工具推薦

常見問題

關於跟進更新、選題與互動方式。

如何第一時間看到新文章?

收藏本部落格列表頁,並在首頁與工具聚合頁留意指南入口。閱讀文章無需註冊或訂閱電子報。

部落格主要寫什麼?

圍繞 JSON 驗證、格式化、轉換與除錯流程,以及 JSON Work 工具更新,與站內工具的本地能力互相呼應。

可以建議教學主題嗎?

可以。請透過關於頁的聯絡方式或 GitHub 回饋;我們會優先安排貼近真實開發情境的教學。