Python處理Json數(shù)據(jù)格式的常見的20種小技巧
處理 JSON 數(shù)據(jù)是 Python 編程中非常常見的任務(wù)。Python 提供了 json 模塊來方便地處理 JSON 數(shù)據(jù)。以下是 20 種處理 JSON 數(shù)據(jù)的常見小技巧,幫助你更高效地完成任務(wù)。
1. 導(dǎo)入 json 模塊
首先,確保導(dǎo)入 json 模塊。
import json
2. 將 Python 對象轉(zhuǎn)換為 JSON 字符串
使用 json.dumps() 方法將 Python 對象轉(zhuǎn)換為 JSON 字符串。
data = {
"name": "Alice",
"age": 30,
"is_student": False
}
json_str = json.dumps(data)
print(json_str) # 輸出: {"name": "Alice", "age": 30, "is_student": false}
3. 將 JSON 字符串轉(zhuǎn)換為 Python 對象
使用 json.loads() 方法將 JSON 字符串轉(zhuǎn)換為 Python 對象。
json_str = '{"name": "Alice", "age": 30, "is_student": false}'
data = json.loads(json_str)
print(data) # 輸出: {'name': 'Alice', 'age': 30, 'is_student': False}
4. 讀取 JSON 文件
使用 json.load() 方法從文件中讀取 JSON 數(shù)據(jù)。
with open('data.json', 'r') as file:
data = json.load(file)
print(data)
5. 寫入 JSON 文件
使用 json.dump() 方法將 Python 對象寫入 JSON 文件。
data = {
"name": "Alice",
"age": 30,
"is_student": False
}
with open('data.json', 'w') as file:
json.dump(data, file)
6. 格式化 JSON 輸出
使用 indent 參數(shù)格式化 JSON 輸出,使其更易讀。
data = {
"name": "Alice",
"age": 30,
"is_student": False
}
json_str = json.dumps(data, indent=4)
print(json_str)
# 輸出:
# {
# "name": "Alice",
# "age": 30,
# "is_student": false
# }
7. 處理日期和時間
使用 json 模塊的 default 參數(shù)處理日期和時間對象。
from datetime import datetime
def json_default(value):
if isinstance(value, datetime):
return value.isoformat()
raise TypeError(f"Type {type(value)} not serializable")
data = {
"name": "Alice",
"timestamp": datetime.now()
}
json_str = json.dumps(data, default=json_default)
print(json_str)
8. 自定義解碼器
使用 object_hook 參數(shù)自定義解碼器。
def custom_decoder(obj):
if 'timestamp' in obj:
obj['timestamp'] = datetime.fromisoformat(obj['timestamp'])
return obj
json_str = '{"name": "Alice", "timestamp": "2023-10-01T12:00:00"}'
data = json.loads(json_str, object_hook=custom_decoder)
print(data) # 輸出: {'name': 'Alice', 'timestamp': datetime.datetime(2023, 10, 1, 12, 0)}
9. 處理 Unicode
使用 ensure_ascii 參數(shù)處理 Unicode 字符。
data = {
"name": "Alice",
"message": "你好,世界!"
}
json_str = json.dumps(data, ensure_ascii=False)
print(json_str) # 輸出: {"name": "Alice", "message": "你好,世界!"}
10. 處理特殊字符
使用 separators 參數(shù)處理特殊字符。
data = {
"name": "Alice",
"age": 30
}
json_str = json.dumps(data, separators=(',', ':'))
print(json_str) # 輸出: {"name":"Alice","age":30}
11. 處理嵌套數(shù)據(jù)
處理嵌套的 JSON 數(shù)據(jù)。
data = {
"name": "Alice",
"details": {
"age": 30,
"is_student": False
}
}
json_str = json.dumps(data)
print(json_str) # 輸出: {"name": "Alice", "details": {"age": 30, "is_student": false}}
12. 處理列表
處理 JSON 列表。
data = [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25}
]
json_str = json.dumps(data)
print(json_str) # 輸出: [{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}]
13. 處理空值
處理 JSON 中的 null 值。
data = {
"name": "Alice",
"age": None
}
json_str = json.dumps(data)
print(json_str) # 輸出: {"name": "Alice", "age": null}
14. 處理布爾值
處理 JSON 中的布爾值。
data = {
"name": "Alice",
"is_student": True
}
json_str = json.dumps(data)
print(json_str) # 輸出: {"name": "Alice", "is_student": true}
15. 處理數(shù)字
處理 JSON 中的數(shù)字。
data = {
"name": "Alice",
"age": 30,
"height": 1.65
}
json_str = json.dumps(data)
print(json_str) # 輸出: {"name": "Alice", "age": 30, "height": 1.65}
16. 處理字符串
處理 JSON 中的字符串。
data = {
"name": "Alice",
"message": "Hello, World!"
}
json_str = json.dumps(data)
print(json_str) # 輸出: {"name": "Alice", "message": "Hello, World!"}
17. 處理特殊字符
處理 JSON 中的特殊字符。
data = {
"name": "Alice",
"message": "This is a \"quoted\" message."
}
json_str = json.dumps(data)
print(json_str) # 輸出: {"name": "Alice", "message": "This is a \"quoted\" message."}
18. 處理異常
處理 JSON 解析異常。
json_str = '{"name": "Alice", "age": 30, "is_student": false}'
try:
data = json.loads(json_str)
print(data)
except json.JSONDecodeError as e:
print(f"JSON 解析錯誤: {e}")
19. 處理大文件
處理大文件時,使用流式處理。
import json
def read_large_json_file(file_path):
with open(file_path, 'r') as file:
for line in file:
data = json.loads(line)
yield data
for item in read_large_json_file('large_data.json'):
print(item)
20. 處理 JSON 數(shù)組
處理 JSON 數(shù)組中的數(shù)據(jù)。
json_str = '[{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}]'
data = json.loads(json_str)
for item in data:
print(item)
# 輸出:
# {'name': 'Alice', 'age': 30}
# {'name': 'Bob', 'age': 25}
總結(jié)
以上是 20 種處理 JSON 數(shù)據(jù)的常見小技巧,涵蓋了從基本的序列化和反序列化到高級的自定義編碼和解碼。通過這些技巧,你可以更高效、更靈活地處理 JSON 數(shù)據(jù)。