如何第一時間看到新文章?
收藏本部落格列表頁,並在首頁與工具聚合頁留意指南入口。閱讀文章無需註冊或訂閱電子報。
使用 Python 標準函式庫安全處理 JSON,涵蓋檔案讀寫、錯誤定位、數字精度、資料轉換、命令列檢查與正式環境注意事項。
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,不要寫入含有密鑰或個資的完整內容。正式匯入也不應悄悄修復輸入後繼續執行。
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 樹狀檢視器。任何工具都不應接收不必要的密鑰或個資。
null。Decimal、字串或最小單位整數。Python 官方 json 模組文件列出完整選項。先使用標準函式庫,在契約需要時加入 Schema 驗證,並讓轉換規則保持明確可稽核。
致力於為開發者提供最佳的 JSON 處理工具
更多文章即將發布...
返回部落格關於跟進更新、選題與互動方式。
收藏本部落格列表頁,並在首頁與工具聚合頁留意指南入口。閱讀文章無需註冊或訂閱電子報。
圍繞 JSON 驗證、格式化、轉換與除錯流程,以及 JSON Work 工具更新,與站內工具的本地能力互相呼應。
可以。請透過關於頁的聯絡方式或 GitHub 回饋;我們會優先安排貼近真實開發情境的教學。