如何在 Python 中讀取和解析 JSON 文件
了解如何使用內建 json 模組在 Python 中讀取、解析和載入 JSON 檔案。掌握將 JSON 字串轉換為字典,反之亦然。
概述
JSON(JavaScript 物件表示法)是 API、設定檔和資料儲存中最受歡迎的資料格式。 Python 附帶了一個內建的「json」模組,讓讀取、解析和寫入 JSON 資料變得異常簡單。由於 JSON 物件完美地映射到 Python 字典,而 JSON 數組映射到 Python 列表,因此使用 JSON 感覺很自然。
若要從外部檔案讀取 JSON,您可以使用 json.load() 函數,該函數解析檔案流並將 JSON 結構轉換為 Python 資料類型。如果 JSON 資料已作為字串載入到記憶體中,則可以使用「json.loads()」函數(「s」代表字串)。選擇正確的函數可以防止解析器崩潰。
使用 JSON 時,最佳做法是處理編碼和潛在的格式錯誤。在 `open()` 語句中使用 `encoding="utf-8"` 可防止您的腳本因特殊字元而失敗。將檔案操作包裝在擷取「json.JSONDecodeError」的「try- except」區塊中,可確保您的應用程式在 JSON 檔案格式錯誤時正常降級。
程式碼和執行輸出
此程式碼示範如何編寫範例 JSON 檔案、將其讀取並解析回 Python 字典,以及處理 JSON 字串。
import json
# Let's write a mock JSON file first
sample_data = {
"user": "developer123",
"skills": ["python", "javascript", "sql"],
"active": True
}
with open("data.json", "w", encoding="utf-8") as f:
json.dump(sample_data, f, indent=4)
# 1. Reading from a JSON file (using json.load)
with open("data.json", "r", encoding="utf-8") as file:
data_from_file = json.load(file)
print("File Content type:", type(data_from_file).__name__)
print("User skill list:", data_from_file["skills"])
# 2. Reading from a JSON string (using json.loads)
json_string = '{"host": "localhost", "port": 5432, "ssl": false}'
data_from_str = json.loads(json_string)
print("\nString Content type:", type(data_from_str).__name__)
print("Database host:", data_from_str["host"])File Content type: dict
User skill list: ['python', 'javascript', 'sql']
String Content type: dict
Database host: localhost逐步實施
- 在腳本中導入內建 json 模組。
- 使用 with open("filename.json", "r",encoding="utf-8") 作為檔案開啟 JSON 檔案。
- 將檔案物件傳遞給 json.load(file) 以將內容解析為 Python 字典。
- 如果需要解析已載入到記憶體中的原始 JSON 字串,請使用 json.loads(string_data)。
常見問題解答
json.load() 和 json.loads() 有什麼不同?
json.load() 接受類似檔案的流物件(從磁碟讀取),而 json.loads() 接受包含 JSON 內容的標準字串或位元組物件(從記憶體讀取)。
如何處理自訂類別的 JSON 序列化錯誤?
Python 的 json 模組預設無法序列化自訂類別實例。您必須提供一個擴展 json.JSONEncoder 的自訂編碼器類,或者先使用輔助方法將實例的屬性提取到字典中。
相關主題
推薦的 Python 資源
透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。