在現代軟體開發中,JSON(JavaScript Object Notation) 幾乎是跨語言的共同語言。
不管是前後端API資料交換、設定檔,甚至是資料儲存,JSON都扮演了關鍵角色。
Python提供了json模組,讓我們可以輕鬆地處理JSON。今天我們就來學習如何讀取、寫入與操作JSON。
範例:
{
"name": "Alice",
"age": 25,
"is_student": false,
"skills": ["Python", "Machine Learning", "Data Analysis"]
}
#Python字典
person = {
"name": "Alice",
"age": 25,
"is_student": False,
"skills": ["Python", "Machine Learning", "Data Analysis"]
}
#轉換成JSON字串
json_str = json.dumps(person, ensure_ascii=False, indent=4)
print(json_str)
輸出:
{
"name": "Alice",
"age": 25,
"is_student": false,
"skills": [
"Python",
"Machine Learning",
"Data Analysis"
]
}
小技巧:
ensure_ascii=False → 保留中文
indent=4 → 美化排版(縮排 4 格)
3.JSON轉換回Python
import json
json_str = '{"name": "Bob", "age": 30, "is_student": true}'
data = json.loads(json_str)
print(data)
print(type(data)) # dict
data = {
"title": "Python 入門",
"author": "Allen",
"chapters": ["基本語法", "資料結構", "函式與模組"]
}
with open("book.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=4)
讀取JSON檔案
import json
with open("book.json", "r", encoding="utf-8") as f:
book = json.load(f)
print(book["title"]) # Python 入門
print(book["chapters"]) # ['基本語法', '資料結構', '函式與模組']
5.JSON在實務中的應用
設定檔(Configuration File)
例如:系統的參數設定、API金鑰存放。
前後端API溝通
後端回傳JSON,前端再解析使用。
資料儲存
適合小型資料儲存,比起資料庫更輕便。
invalid_json = '{"name": "Tom", "age": }' # 少了數字
try:
data = json.loads(invalid_json)
except json.JSONDecodeError as e:
print("JSON 格式錯誤:", e)
今天我們學會了JSON的基本概念、Python與JSON的轉換、檔案讀寫,以及JSON在設定檔、API與資料儲存的實務應用。
掌握JSON處理能力後,我們就能更好地與不同系統、應用程式溝通。