共計 807 個字符,預計需要花費 3 分鐘才能閱讀完成。
在 Python 中,處理 JSON 數據十分簡單。可以使用 json
模塊來加載和轉換 JSON 數據:
1. 將 JSON 字符串轉換為 Python 對象
import json
json_str = '{"name": "Alice", "age": 25}'
data = json.loads(json_str)
print(data["name"]) # 輸出:Alice
在上述示例中,首先使用 json.loads()
函數將 JSON 字符串轉換為 Python 對象。然后,可以像訪問普通字典一樣通過鍵來訪問 JSON 數據的值。
2. 將 Python 對象轉換為 JSON 字符串
import json
data = {"name": "Alice", "age": 25}
json_str = json.dumps(data)
print(json_str) # 輸出:{"name": "Alice", "age": 25}
在上述示例中,使用 json.dumps()
函數將 Python 對象轉換為 JSON 字符串。
3. 讀取 JSON 文件并將其轉換為 Python 對象
import json
with open("data.json") as file:
data = json.load(file)
print(data["name"]) # 輸出:Alice
在上述示例中,使用 json.load()
函數從文件中讀取 JSON 數據并將其轉換為 Python 對象。
4. 將 Python 對象寫入 JSON 文件
import json
data = {"name": "Alice", "age": 25}
with open("data.json", "w") as file:
json.dump(data, file)
在上述示例中,使用 json.dump()
函數將 Python 對象寫入 JSON 文件。
以上是一些常見的 JSON 數據處理操作。根據具體需求,還可以使用更多的 json
模塊函數和方法來處理和操作 JSON 數據。
丸趣 TV 網 – 提供最優質的資源集合!
正文完