在現代開發中,JSON 是非常常見的資料格式,例如:
- API 回傳資料
- 設定檔(config)
- 前後端資料交換
這篇教學會帶你用 Python 讀取 JSON 檔案 👍
📥 匯入模組
import json
📂 讀取 JSON 檔案
with open('data.json', 'r', encoding='utf-8') as file: data = json.load(file)📌 說明:
open():開啟檔案json.load():將 JSON 轉為 Python 資料- 使用
with可以自動關閉檔案 - 建議加上
encoding='utf-8'(避免中文亂碼)
🧠 JSON 轉成 Python 長什麼樣?
例如 JSON:
{ "name": "John", "age": 30, "city": "New York"}
👉 會變成 Python 的:
{ "name": "John", "age": 30, "city": "New York"}
(其實就是 dictionary)
🔍 存取資料
name = data["name"]age = data["age"]city = data["city"]print(name, age, city)
🔄 迭代資料(陣列)
如果 JSON 是一個列表:
[ {"name": "John"}, {"name": "Amy"}]
可以這樣處理:
for item in data: print(item["name"])
⚠️ 常見注意事項
1️⃣ Key 不存在會報錯
data["name"]
👉 建議用:
data.get("name")
2️⃣ JSON 格式錯誤會讀取失敗
👉 常見錯誤:
- 少逗號
- 單引號(應使用雙引號)
3️⃣ 中文亂碼問題
👉 一定要加:
encoding='utf-8'
🎯 小結
透過 json 模組,你可以:
✔ 讀取 JSON 檔案
✔ 轉換為 Python dict / list ✔ 存取與操作資料 ✔ 處理 API 回傳內容














