Python使用json模塊讀取和寫入JSON數(shù)據(jù)
在現(xiàn)代軟件開發(fā)中,JSON(JavaScript Object Notation) 已成為最流行的數(shù)據(jù)交換格式之一。Python 提供了內(nèi)置的 json 模塊,使得我們可以方便地解析 JSON 數(shù)據(jù)(讀?。┖蜕?JSON 數(shù)據(jù)(寫入)。無論是 Web API 交互、配置文件存儲,還是數(shù)據(jù)序列化,json 模塊都是不可或缺的工具。本文將詳細(xì)介紹 json 模塊的讀取、寫入、格式化、編碼解碼等操作,并結(jié)合實(shí)際案例展示其應(yīng)用。
1. JSON 與 Python 數(shù)據(jù)類型的映射關(guān)系
Python 的 json 模塊可以在 Python 基本數(shù)據(jù)類型和 JSON 數(shù)據(jù)類型之間相互轉(zhuǎn)換,映射關(guān)系如下:
Python 類型 | JSON 類型 | 示例 |
---|---|---|
dict | object | {"name": "Alice", "age": 25} |
list / tuple | array | ["apple", "banana", "cherry"] |
str | string | "hello" |
int / float | number | 42, 3.14 |
bool | true / false | true, false |
None | null | null |
2. 讀取 JSON 數(shù)據(jù)
Python 可以從字符串或文件中讀取 JSON 數(shù)據(jù)。
2.1 從 JSON 字符串解析
import json json_str = '{"name": "Alice", "age": 25, "city": "New York"}' # 將 JSON 字符串轉(zhuǎn)換為 Python 字典 data = json.loads(json_str) print(data["name"]) # 輸出: Alice print(type(data)) # 輸出: <class 'dict'>
json.loads() 作用:
- 輸入:JSON 格式的字符串。
- 輸出:轉(zhuǎn)換為 Python dict 對象。
2.2 從 JSON 文件讀取
假設(shè)有一個 data.json 文件:
{ "name": "Bob", "age": 30, "skills": ["Python", "Java", "C++"] }
使用 json.load() 讀取文件:
with open("data.json", "r", encoding="utf-8") as file: data = json.load(file) print(data["name"]) # 輸出: Bob print(data["skills"]) # 輸出: ['Python', 'Java', 'C++']
json.load() 作用:
- 輸入:JSON 文件對象。
- 輸出:Python dict 對象。
3. 寫入 JSON 數(shù)據(jù)
Python 可以將數(shù)據(jù)寫入字符串或文件。
3.1 將 Python 對象轉(zhuǎn)換為 JSON 字符串
import json data = { "name": "Charlie", "age": 28, "city": "San Francisco" } # 將 Python 字典轉(zhuǎn)換為 JSON 字符串 json_str = json.dumps(data) print(json_str) print(type(json_str)) # 輸出: <class 'str'>
json.dumps() 作用:
- 輸入:Python dict、list、str 等。
- 輸出:JSON 格式的字符串。
3.2 將 Python 對象寫入 JSON 文件
import json data = { "name": "David", "age": 35, "languages": ["Python", "Go", "Rust"] } # 寫入 JSON 文件 with open("output.json", "w", encoding="utf-8") as file: json.dump(data, file) print("數(shù)據(jù)已寫入 output.json")
json.dump() 作用:
- 輸入:Python dict(或其他可序列化對象)。
- 輸出:寫入 JSON 文件。
4. JSON 格式化輸出(縮進(jìn)、排序)
默認(rèn)情況下,JSON 生成的字符串是緊湊的,不易閱讀:
data = {"name": "Eve", "age": 26, "city": "Paris"} json_str = json.dumps(data) print(json_str) # 輸出: {"name": "Eve", "age": 26, "city": "Paris"}
為了更清晰地輸出 JSON,可以使用 indent 參數(shù):
json_str = json.dumps(data, indent=4) print(json_str)
輸出(格式化 JSON):
{ "name": "Eve", "age": 26, "city": "Paris" }
如果希望按鍵名排序:
json_str = json.dumps(data, indent=4, sort_keys=True) print(json_str)
輸出(按鍵排序):
{ "age": 26, "city": "Paris", "name": "Eve" }
5. 處理 JSON 編碼與解碼(對象序列化)
如果 JSON 數(shù)據(jù)包含自定義對象,默認(rèn) json.dumps() 無法處理:
import json from datetime import datetime data = {"name": "Alice", "time": datetime.now()} # 會報錯:Object of type datetime is not JSON serializable json_str = json.dumps(data)
可以使用 default 參數(shù),將 datetime 對象轉(zhuǎn)換為字符串:
def json_serial(obj): if isinstance(obj, datetime): return obj.isoformat() # 轉(zhuǎn)換為 ISO 8601 時間格式 raise TypeError("Type not serializable") json_str = json.dumps(data, default=json_serial, indent=4) print(json_str)
示例輸出:
{ "name": "Alice", "time": "2024-02-04T14:00:00.123456" }
6. 處理 JSON 解析錯誤
解析 JSON 時,可能會遇到格式錯誤:
import json invalid_json = '{"name": "Tom", "age": 30,}' # 末尾多了逗號 try: data = json.loads(invalid_json) except json.JSONDecodeError as e: print(f"JSON 解析錯誤: {e}")
輸出:
JSON 解析錯誤: Expecting property name enclosed in double quotes
7. JSON 讀寫的最佳實(shí)踐
讀取 JSON 時使用 try-except 捕獲異常
try: with open("config.json", "r", encoding="utf-8") as file: config = json.load(file) except (FileNotFoundError, json.JSONDecodeError) as e: print(f"錯誤: {e}")
寫入 JSON 時使用 indent=4 讓數(shù)據(jù)更易讀
json.dump(data, file, indent=4)
處理非標(biāo)準(zhǔn)數(shù)據(jù)類型時,使用 default 進(jìn)行序列化
json.dumps(data, default=json_serial)
8. 結(jié)論
操作 | 方法 |
---|---|
從字符串讀取 JSON | json.loads(json_str) |
從文件讀取 JSON | json.load(file) |
將 Python 對象轉(zhuǎn)換為 JSON 字符串 | json.dumps(obj) |
將 Python 對象寫入 JSON 文件 | json.dump(obj, file) |
格式化 JSON(縮進(jìn)) | json.dumps(obj, indent=4) |
解析錯誤處理 | json.JSONDecodeError |
處理非標(biāo)準(zhǔn)數(shù)據(jù)類型 | default=json_serial |
Python 的 json
模塊提供了強(qiáng)大且易用的 JSON 處理能力,合理使用這些方法,可以讓你的代碼更加高效、可維護(hù)!
以上就是Python使用json模塊讀取和寫入JSON數(shù)據(jù)的詳細(xì)內(nèi)容,更多關(guān)于Python讀取和寫入JSON數(shù)據(jù)的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python實(shí)現(xiàn)自定義順序、排列寫入數(shù)據(jù)到Excel的方法
這篇文章主要介紹了Python實(shí)現(xiàn)自定義順序、排列寫入數(shù)據(jù)到Excel的方法,涉及Python針對Excel文件的數(shù)據(jù)處理及讀寫相關(guān)操作技巧,需要的朋友可以參考下2018-04-04Python調(diào)用百度根據(jù)經(jīng)緯度查詢地址的示例代碼
今天小編就為大家分享一篇Python調(diào)用百度根據(jù)經(jīng)緯度查詢地址的示例代碼,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07YOLOv5車牌識別實(shí)戰(zhàn)教程(一)引言與準(zhǔn)備工作
這篇文章主要介紹了YOLOv5車牌識別實(shí)戰(zhàn)教程(一)引言與準(zhǔn)備工作,在這個教程中,我們將一步步教你如何使用YOLOv5進(jìn)行車牌識別,幫助你快速掌握YOLOv5車牌識別技能,需要的朋友可以參考下2023-04-04Python通過pytesseract庫實(shí)現(xiàn)識別圖片中的文字
Pytesseract是一個Python的OCR庫,它可以識別圖片中的文本并將其轉(zhuǎn)換成文本形式。本文就來用pytesseract庫實(shí)現(xiàn)識別圖片中的文字,感興趣的可以了解一下2023-05-05python實(shí)現(xiàn)與Oracle數(shù)據(jù)庫交互操作示例
這篇文章主要為大家介紹了python實(shí)現(xiàn)與Oracle數(shù)據(jù)庫交互操作示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家,多多進(jìn)步,早日升職加薪2021-10-10Python 多進(jìn)程原理及實(shí)現(xiàn)
這篇文章主要介紹了Python 多進(jìn)程原理及實(shí)現(xiàn),幫助大家更好的理解和使用python,感興趣的朋友可以了解下2020-12-12