本文目录导读:

我来详细介绍Python中解析JSON数据的各种方法和案例。
JSON 基础解析
1 从字符串解析JSON
import json
# JSON字符串
json_str = '{"name": "张三", "age": 25, "city": "北京"}'
# 解析JSON字符串为Python字典
data = json.loads(json_str)
print(data)
print(type(data)) # <class 'dict'>
print(data['name']) # 张三
2 从文件读取JSON
import json
# 方式1:使用json.load()
with open('data.json', 'r', encoding='utf-8') as f:
data = json.load(f)
print(data)
# 方式2:先读取字符串再解析
with open('data.json', 'r', encoding='utf-8') as f:
content = f.read()
data = json.loads(content)
print(data)
3 JSON数组解析
import json
# JSON数组
json_array = '[{"name": "张三", "age": 25}, {"name": "李四", "age": 30}]'
# 解析为Python列表
users = json.loads(json_array)
print(type(users)) # <class 'list'>
for user in users:
print(f"姓名: {user['name']}, 年龄: {user['age']}")
嵌套JSON解析
1 处理复杂嵌套结构
import json
# 嵌套的JSON结构
complex_json = '''
{
"company": "ABC科技",
"employees": [
{
"id": 1,
"name": "张三",
"department": "开发部",
"skills": ["Python", "Java", "SQL"],
"contact": {
"email": "zhangsan@email.com",
"phone": "13800138001"
}
},
{
"id": 2,
"name": "李四",
"department": "运维部",
"skills": ["Docker", "Kubernetes", "Linux"],
"contact": {
"email": "lisi@email.com",
"phone": "13800138002"
}
}
],
"departments": ["开发部", "运维部", "测试部"]
}
'''
data = json.loads(complex_json)
# 解析嵌套数据
company = data['company']
print(f"公司名称: {company}")
for emp in data['employees']:
print(f"\n员工信息:")
print(f" 姓名: {emp['name']}")
print(f" 部门: {emp['department']}")
print(f" 技能: {', '.join(emp['skills'])}")
print(f" 邮箱: {emp['contact']['email']}")
高级解析技巧
1 使用自定义解码器
import json
from datetime import datetime
class CustomDecoder(json.JSONDecoder):
def decode(self, s):
# 自定义解码逻辑
result = super().decode(s)
return self.convert_dates(result)
def convert_dates(self, obj):
if isinstance(obj, dict):
for key, value in obj.items():
if key == 'date' and isinstance(value, str):
obj[key] = datetime.strptime(value, '%Y-%m-%d')
else:
obj[key] = self.convert_dates(value)
return obj
# 测试
json_str = '{"event": "会议", "date": "2024-01-15"}'
data = json.loads(json_str, cls=CustomDecoder)
print(data) # {'event': '会议', 'date': datetime.datetime(2024, 1, 15, 0, 0)}
2 使用object_hook进行转换
import json
from collections import namedtuple
def json_to_object(data):
"""将JSON字典转换为命名元组"""
return namedtuple('Object', data.keys())(*data.values())
# 使用object_hook参数
json_str = '{"name": "张三", "age": 25, "city": "北京"}'
data = json.loads(json_str, object_hook=json_to_object)
print(data.name) # 张三
print(data.age) # 25
错误处理
1 处理解析异常
import json
def safe_json_parse(json_string):
"""安全解析JSON字符串"""
try:
data = json.loads(json_string)
return data, None
except json.JSONDecodeError as e:
return None, f"JSON解析错误: {e}"
except Exception as e:
return None, f"未知错误: {e}"
# 测试
test_jsons = [
'{"name": "张三"}', # 有效JSON
'{"name": "张三"', # 无效JSON
'{"age": "25"}', # 有效JSON
]
for test in test_jsons:
data, error = safe_json_parse(test)
if error:
print(f"错误: {error}")
else:
print(f"成功解析: {data}")
2 验证JSON格式
import json
def validate_json(json_string):
"""验证JSON格式是否有效"""
try:
json.loads(json_string)
return True
except json.JSONDecodeError:
return False
# 使用示例
json_data = '{"name": "测试"}'
print(f"JSON格式有效: {validate_json(json_data)}")
bad_json = '{name: "测试"}'
print(f"JSON格式有效: {validate_json(bad_json)}")
实际应用案例
1 API响应解析
import json
import requests # 需要安装:pip install requests
def parse_api_response():
"""解析API响应数据"""
# 模拟API响应
api_response = '''
{
"status": "success",
"code": 200,
"data": {
"total": 2,
"items": [
{"id": 1, "title": "文章1", "views": 100},
{"id": 2, "title": "文章2", "views": 200}
]
},
"message": "请求成功"
}
'''
response = json.loads(api_response)
# 检查状态
if response['status'] == 'success' and response['code'] == 200:
articles = response['data']['items']
total = response['data']['total']
print(f"共 {total} 篇文章:")
for article in articles:
print(f" ID: {article['id']}, 标题: {article['title']}, 浏览: {article['views']}")
else:
print(f"请求失败: {response['message']}")
parse_api_response()
2 配置文件解析
import json
import os
def load_config(config_file='config.json'):
"""加载配置文件"""
default_config = {
"database": {
"host": "localhost",
"port": 3306,
"username": "root",
"password": ""
},
"app": {
"debug": True,
"port": 8000
}
}
try:
if os.path.exists(config_file):
with open(config_file, 'r', encoding='utf-8') as f:
config = json.load(f)
# 合并默认配置
for key in default_config:
if key not in config:
config[key] = default_config[key]
return config
else:
print(f"配置文件 {config_file} 不存在,使用默认配置")
return default_config
except json.JSONDecodeError as e:
print(f"配置文件格式错误: {e}")
return default_config
# 使用示例
config = load_config()
print(config['database']['host']) # localhost
这些案例涵盖了Python中JSON解析的各种实际应用场景,根据你的具体需求,可以选择合适的解析方式。