1. JSON数据处理基础
JSON作为现代应用开发中最常用的数据交换格式,其轻量级和易读性使其成为API交互的首选。Python内置的json模块提供了完整的JSON处理能力,我们先从最基础的解析开始。
1.1 JSON字符串解析
json.loads()是将JSON字符串转换为Python对象的核心方法。实际开发中需要注意几个关键点:
python复制import json
# 标准JSON字符串解析
json_str = '{"name": "Alice", "age": 25, "is_active": true}'
data = json.loads(json_str)
# 类型转换对照
print(type(data["name"])) # <class 'str'>
print(type(data["age"])) # <class 'int'>
print(type(data["is_active"])) # <class 'bool'>
# 处理嵌套结构
complex_json = '''
{
"users": [
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"}
],
"meta": {
"page": 1,
"total": 100
}
}
'''
parsed_data = json.loads(complex_json)
print(parsed_data["users"][0]["name"]) # Alice
注意:JSON中的true/false/null会分别转换为Python的True/False/None,数字会根据值自动转为int或float
1.2 文件读写操作
实际项目中更多是处理JSON文件而非字符串。文件操作时需特别注意编码问题:
python复制# 写入JSON文件的最佳实践
data = {
"server": {
"host": "127.0.0.1",
"ports": [8000, 8001, 8002]
},
"timeout": 30.5
}
with open("config.json", "w", encoding="utf-8") as f:
json.dump(data, f,
indent=2, # 缩进美化
ensure_ascii=False, # 允许非ASCII字符
sort_keys=True) # 键排序
# 读取JSON文件的安全写法
try:
with open("config.json", "r", encoding="utf-8") as f:
config = json.load(f)
print(config["server"]["ports"][0]) # 8000
except FileNotFoundError:
print("配置文件不存在")
except json.JSONDecodeError:
print("配置文件格式错误")
1.3 特殊数据类型处理
JSON标准数据类型有限,处理Python特有类型时需要自定义编码器:
python复制from datetime import datetime
from decimal import Decimal
class EnhancedJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
if isinstance(obj, Decimal):
return float(obj)
if isinstance(obj, set):
return list(obj)
return super().default(obj)
# 使用自定义编码器
data = {
"timestamp": datetime.now(),
"price": Decimal("19.99"),
"tags": {"python", "json", "xml"}
}
json_str = json.dumps(data, cls=EnhancedJSONEncoder)
print(json_str)
# 输出示例:{"timestamp": "20
