abstract business code coder

如何在 Python 中讀取和操作 JSON 檔案

JSON (JavaScript Object Notation) 是一種輕量級的數據交換格式。

在 Python 中,我們可以使用 json 模組來處理 JSON 數據。

本文將教您如何在 Python 中讀取和操作 JSON 檔案。

將 JSON 字串轉換為 Python 物件

JSON 數據經常存儲在字串中,這是使用 API 時的常見場景。

要將 JSON 字串解析為 Python 物件,我們可以使用 json 模組。

首先,需要導入 Python 的 json 模組:

import json

然後,使用 json.loads() 函數將 JSON 字串轉換為 Python 物件:

json_str = '{"name": "Tom", "age": 30}'
data = json.loads(json_str)
print(data)

輸出結果將是一個字典:

{'name': 'Tom', 'age': 30}

將 JSON 檔案讀取為字典

要將 JSON 檔案讀取為字典,我們需要使用 json 模組以及 Python 的內置 open() 函數。

首先,導入 json 模組:

import json

接下來,使用 open() 函數讀取 JSON 檔案,並利用 json.load() 函數將 JSON 字串轉換為 Python 物件:

with open('data.json', 'r') as f:
    data = json.load(f)
print(data)

讀取和寫入 JSON 檔案

使用 json 模組,我們可以方便地讀取和寫入 JSON 檔案。以下是讀取 JSON 檔案的範例:

import json

with open('data.json', 'r') as f:
    data = json.load(f)
print(data)

以下是寫入 JSON 檔案的範例:

import json

data = {'name': 'Tom', 'age': 30}

with open('output.json', 'w') as f:
    json.dump(data, f)

這樣,我們就可以在 Python 中輕鬆地讀取和操作 JSON 檔案了。

Similar Posts

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *