WeHelp
學習各式各樣的內建函式、類別、物件、模組等等工具,完成各種 Python 基礎應用。
  1. 字串的操作
  2. 列表的操作
  3. 字典的操作
  4. 數學、統計模組
  5. 文字檔案讀取、寫入
  6. CSV 檔案讀取、寫入
  7. JSON 檔案讀取、寫入
  8. ZIP 壓縮檔案和解壓縮
  9. HTTP 網路連線請求
  10. 網頁爬蟲程式
  11. 日期與時間
  12. 正規表達式
JSON 檔案讀取、寫入
## 什麼是 JSON? JSON(JavaScript Object Notation)是一種輕量、純文字的資料交換格式,常用於: - 儲存設定檔 - API 傳遞資料 - 程式之間交換結構化資料 JSON 的資料結構主要包含: | JSON 類型 | Python 對應類型 | |---|---| | object(物件) | `dict` | | array(陣列) | `list` | | string(字串) | `str` | | number(數字) | `int`、`float` | | true / false | `True` / `False` | | null | `None` | 例如,一個 `user.json` 檔案可能如下: ```json { "name": "王小明", "age": 25, "is_student": true, "skills": ["Python", "SQL"] } ``` JSON 的字串與屬性名稱必須使用雙引號,不能使用單引號。 --- ## 使用 Python 內建 `json` 模組 Python 不需要另外安裝套件,只要匯入內建的 `json` 模組即可: ```python import json ``` ### 1. 從 JSON 檔案讀取資料 假設目前有一個 `user.json`: ```json { "name": "王小明", "age": 25, "is_student": true, "skills": ["Python", "SQL"] } ``` Python 讀取範例: ```python import json with open("user.json", "r", encoding="utf-8") as file: user = json.load(file) print("姓名:", user["name"]) print("年齡:", user["age"]) print("技能:", ", ".join(user["skills"])) ``` 執行結果: ```text 姓名: 王小明 年齡: 25 技能: Python, SQL ``` 說明: - `json.load(file)`:從檔案讀取 JSON,並轉換成 Python 的字典或串列。 - `encoding="utf-8"`:確保中文正常讀取。 - `with open(...)`:使用完檔案後會自動關閉檔案。 --- ### 2. 將資料寫入 JSON 檔案 以下範例將員工資料寫入 `employee.json`: ```python import json employee = { "id": 1001, "name": "陳小華", "department": "資訊部", "skills": ["Python", "Docker"], "active": True } with open("employee.json", "w", encoding="utf-8") as file: json.dump(employee, file, ensure_ascii=False, indent=4) print("資料已寫入 employee.json") ``` 產生的 `employee.json` 內容如下: ```json { "id": 1001, "name": "陳小華", "department": "資訊部", "skills": [ "Python", "Docker" ], "active": true } ``` 說明: - `json.dump(data, file)`:將 Python 資料寫入 JSON 檔案。 - `ensure_ascii=False`:保留中文,不將中文轉成 `\u` 編碼。 - `indent=4`:讓 JSON 以縮排格式儲存,方便閱讀。 - 使用 `"w"` 模式會覆寫原本檔案;若檔案不存在,Python 會建立新檔案。 另外,`json.dumps()` 和 `json.loads()` 則是用於在「字串」與 Python 資料之間轉換,而不是直接操作檔案。
相關學習地圖、教學課程
Python 資料工程
從 0 開始,成為資料工程師的學習路徑。
Python 後端工程、資料庫
從 0 開始,成為後端工程師的學習路徑。