在Python中,對JSON數據進行增刪改查及加載保存操作,主要通過內置的json
模塊實現。
一、基礎操作
1. 加載JSON數據
? 從文件加載
使用json.load()
讀取JSON文件并轉換為Python對象(字典/列表):
import json
with open('data.json', 'r', encoding='utf-8') as f:data = json.load(f)
? 從字符串加載
使用json.loads()
將JSON字符串解析為Python對象:
json_str = '{"name": "Alice", "age": 30}'
data = json.loads(json_str)
2. 保存JSON數據
? 保存到文件
使用json.dump()
將Python對象寫入JSON文件:
with open('data.json', 'w') as f:json.dump(data, f, indent=4) # indent參數格式化輸出
? 轉換為字符串
使用json.dumps()
生成JSON字符串:
json_str = json.dumps(data, ensure_ascii=False) # 處理中文字符
二、數據操作
1. 查詢數據
通過字典鍵或列表索引訪問數據:
# 示例JSON結構:{"students": [{"id": 1, "name": "Alice"}, ...]}
print(data['students'][0]['name']) # 輸出:Alice
2. 新增數據
向列表或字典中添加新條目:
# 添加新學生
new_student = {"id": 4, "name": "David"}
data['students'].append(new_student) # 列表添加
3. 修改數據
直接修改字典或列表的值:
# 修改第一個學生的年齡
data['students'][0]['age'] = 25
4. 刪除數據
使用del
或pop()
刪除條目:
# 刪除第一個學生
del data['students'][0] # 或 data['students'].pop(0)
三、進階操作
1. 處理復雜結構
? 嵌套數據操作
通過逐層訪問修改嵌套數據:
data['root']['child']['key'] = 'value' # 修改多層嵌套數據
? 條件查詢與修改
結合循環和條件語句:
# 將所有年齡大于20的學生標記為成人
for student in data['students']:if student['age'] > 20:student['is_adult'] = True #
2. 處理特殊數據類型
? 日期/時間對象
自定義編碼器處理非標準類型:
from datetime import datetime
def custom_encoder(obj):if isinstance(obj, datetime):return obj.isoformat()raise TypeError("Type not serializable")json_str = json.dumps(data, default=custom_encoder)
? 自定義解碼器
反序列化時還原特殊類型:
def custom_decoder(dct):if 'timestamp' in dct:dct['timestamp'] = datetime.fromisoformat(dct['timestamp'])return dct
data = json.loads(json_str, object_hook=custom_decoder) #
四、注意事項
-
文件模式:
?'r'
用于讀取,'w'
會覆蓋原文件,'r+'
可讀寫但不保留舊內容。 -
編碼問題:
處理中文時需設置ensure_ascii=False
。