Python 中如何高效解析 JSON 数据并处理常见格式错误与异常情况

在现代软件开发中,JSON(JavaScript Object Notation)已成为数据交换的标准格式。无论是从 API 获取数据、读取配置文件,还是处理数据库记录,我们几乎无时无刻不在与 JSON 打交道。然而,处理 JSON 数据并非总是那么直接。数据可能来自不可靠的来源,格式可能不规范,或者数据结构可能与我们的预期不符。
本文将深入探讨如何在 Python 中高效解析 JSON 数据,并详细讲解如何处理常见的格式错误与异常情况。我们将从基础开始,逐步深入到高级技巧和最佳实践。
1. JSON 解析基础:
json
模块
Python 标准库中的
json
模块是处理 JSON 数据的基石。它提供了简单易用的接口来序列化(将 Python 对象转换为 JSON 字符串)和反序列化(将 JSON 字符串转换为 Python 对象)数据。
1.1 基本用法:
json.loads()
和
json.load()
json.loads()
: 用于解析 JSON
字符串
。
json.load()
: 用于从
文件对象
中读取并解析 JSON 数据。
import json

# 示例 1: 解析 JSON 字符串
json_string = ‘{“name”: “Alice”, “age”: 30, “is_student”: false}’
data = json.loads(json_string)
print(f”解析后的数据类型: {type(data)}”)
print(f”解析后的数据: {data}”)
print(f”访问数据: {data[‘name’]}”)

# 示例 2: 从文件中读取 JSON
# 假设有一个名为 ‘config.json’ 的文件,内容为: {“host”: “localhost”, “port”: 8080}
# with open(‘config.json’, ‘r’) as f:
# config = json.load(f)
# print(f”配置: {config}”)
输出:
解析后的数据类型:
解析后的数据: {‘name’: ‘Alice’, ‘age’: 30, ‘is_student’: False}
访问数据: Alice
关键点:
JSON 对象被解析为 Python 字典 (
dict
)。
JSON 数组被解析为 Python 列表 (
list
)。
JSON 字符串、数字、布尔值和
null
分别对应 Python 的
str
、
int
/
float
、
bool
和
None
。
1.2 序列化基础:
json.dumps()
和
json.dump()
json.dumps()
: 将 Python 对象转换为 JSON
字符串
。
json.dump()
: 将 Python 对象写入
文件对象
。
import json

python_dict = {
“name”: “Bob”,
“age”: 25,
“skills”: [“Python”, “Django”],
“active”: True,
“profile”: None
}

# 示例 1: 转换为 JSON 字符串
json_string = json.dumps(python_dict)
print(f”JSON 字符串: {json_string}”)

# 示例 2: 美化输出 (indent=4)
pretty_json_string = json.dumps(python_dict, indent=4)
print(f”美化的 JSON 字符串:\n{pretty_json_string}”)

# 示例 3: 写入文件
# with open(‘output.json’, ‘w’) as f:
# json.dump(python_dict, f, indent=4)
输出:
JSON 字符串: {“name”: “Bob”, “age”: 25, “skills”: [“Python”, “Django”], “active”: true, “profile”: null}
美化的 JSON 字符串:
{
“name”: “Bob”,
“age”: 25,
“skills”: [
“Python”,
“Django”
],
“active”: true,
“profile”: null
}
2. 高效解析策略
仅仅能解析 JSON 是不够的,我们还需要考虑性能和内存使用,特别是在处理大型 JSON 文件或高频请求时。
2.1 处理大型 JSON 文件:流式解析 (ijson)
当 JSON 文件非常大(例如几百 MB 或几个 GB)时,一次性将其加载到内存中会导致
MemoryError
或显著降低系统性能。此时,我们需要使用流式解析库,如
ijson
。
ijson
允许我们像迭代器一样逐个处理 JSON 数组中的元素,而无需将整个文件加载到内存。
安装 ijson:
pip install ijson
示例:处理大型 JSON 数组文件
假设我们有一个名为
large_data.json
的文件,内容如下:
[
{“id”: 1, “value”: “data1”},
{“id”: 2, “value”: “data2″},
…
]
使用
ijson
解析:
import ijson

# 假设文件很大,我们只关心每个对象的 ‘id’ 并计算总和
total_id = 0
count = 0

# ‘item’ 表示我们迭代数组中的每个元素
with open(‘large_data.json’, ‘rb’) as f:
# 使用 ijson.items 迭代解析
for item in ijson.items(f, ‘item’):
total_id += item[‘id’]
count += 1
# 可以在这里处理每个 item,例如插入数据库
# process_item(item)

print(f”处理了 {count} 个对象,ID 总和为: {total_id}”)
为什么高效?
ijson
在底层使用 YAJL (Yet Another JSON Library) C 库,速度非常快。
它不会一次性将所有数据加载到 Python 内存中,而是按需解析流。
2.2 使用
orjson
提升解析速度
如果你追求极致的性能,
orjson
是一个极佳的选择。它是用 Rust 编写的 Python 库,通常比标准库
json
和其他库(如
ujson
、
simplejson
)快得多。
安装 orjson:
pip install orjson
性能对比示例:
import json
import orjson
import time

# 生成一个较大的 JSON 字符串
large_data = [{“id”: i, “name”: f”user_{i}”, “data”: [1, 2, 3] * 10} for i in range(10000)]
json_str = json.dumps(large_data).encode(‘utf-8’)

# 测试标准库 json
start_time = time.time()
for _ in range(100):
json.loads(json_str)
json_time = time.time() – start_time

# 测试 orjson
start_time = time.time()
for _ in range(100):
orjson.loads(json_str)
orjson_time = time.time() – start_time

print(f”标准库 json 耗时: {json_time:.4f} 秒”)
print(f”orjson 耗时: {orjson_time:.4f} 秒”)
print(f”orjson 比 json 快约 {json_time / orjson_time:.2f} 倍”)
注意:
orjson.loads()
接受
bytes
或
str
。
orjson.dumps()
返回
bytes
,这在处理网络传输或文件写入时通常更高效。
3. 处理常见格式错误与异常情况
JSON 数据的来源往往不可靠,因此健壮的错误处理至关重要。
3.1 基础异常捕获:
json.JSONDecodeError
最基础的错误是 JSON 格式本身无效,例如缺少引号、逗号错误、未闭合的括号等。这会引发
json.JSONDecodeError
(在 Python 3.5+ 中是
ValueError
的子类)。
import json

invalid_json_strings = [
‘{“name”: “Alice”, “age”: 30}’, # 有效
‘{“name”: “Alice”, “age”: 30,}’, # 无效:末尾多余的逗号 (Python json 模块严格模式下会报错)
‘{“name”: “Alice”, “age”: 30’, # 无效:缺少右花括号
‘{“name”: “Alice”, “age”: “30”}’, # 有效:年龄是字符串
‘{“name”: “Alice”, “age”: 30, “is_student”: false’, # 无效:缺少逗号和右括号
‘{“name”: “Alice”, “age”: 30, “is_student”: false,}’, # 无效:末尾逗号
]

for i, json_str in enumerate(invalid_json_strings):
try:
data = json.loads(json_str)
print(f”示例 {i+1}: 解析成功 -> {data}”)
except json.JSONDecodeError as e:
print(f”示例 {i+1}: 解析失败!”)
print(f” 错误类型: {type(e).__name__}”)
print(f” 错误信息: {e}”)
print(f” 错误位置: 第 {e.lineno} 行, 第 {e.colno} 列”)
print(f” 错误上下文: {e.doc}”)
print(“-” * 20)
输出分析:
json.JSONDecodeError
提供了非常详细的错误信息,包括错误发生的行号 (
lineno
)、列号 (
colno
) 以及错误的文档内容 (
doc
)。这对于调试非常有帮助。
注意:
Python 的
json
模块默认
不允许
在 JSON 对象或数组末尾有 trailing comma(多余的逗号)。这与 JavaScript 的宽松处理不同。
3.2 处理非 JSON 字符串或非预期类型
有时,你可能收到一个空字符串、
None
,或者根本不是 JSON 格式的字符串(例如 HTML 错误页面)。
import json

def safe_parse_json(raw_data):
if not raw_data: # 检查空字符串或 None
print(“输入为空,无法解析”)
return None

try:
return json.loads(raw_data)
except json.JSONDecodeError as e:
print(f”JSON 解析错误: {e}”)
# 这里可以记录日志,或者返回一个默认值
return {“error”: “Invalid JSON”, “raw”: raw_data[:100]} # 截断原始数据

# 测试
print(safe_parse_json(”))
print(safe_parse_json(None)) # 这里会抛出 TypeError,需要进一步处理
print(safe_parse_json(‘Error‘))
改进版:
import json

def robust_parse_json(raw_data):
# 检查输入是否为 None
if raw_data is None:
return {“error”: “Input is None”}

# 检查输入是否为字符串
if not isinstance(raw_data, str):
return {“error”: f”Input is not a string, got {type(raw_data)}”}

# 检查是否为空字符串
if not raw_data.strip():
return {“error”: “Input is empty or whitespace”}

try:
return json.loads(raw_data)
except json.JSONDecodeError as e:
return {“error”: f”JSONDecodeError: {e}”, “raw”: raw_data[:200]}

# 测试
print(robust_parse_json(None))
print(robust_parse_json(”))
print(robust_parse_json(‘ ‘))
print(robust_parse_json(‘Error‘))
print(robust_parse_json(‘{“valid”: true}’))
3.3 处理数据结构不匹配(KeyError, TypeError)
即使 JSON 格式正确,其内部结构也可能与你的代码预期不符。例如,你期望某个键存在,但它缺失了;或者你期望一个值是数字,但它却是字符串。
场景:
从 API 获取用户数据,期望
user.id
是整数,
user.name
是字符串。
import json

# 模拟不同来源的 JSON 数据
api_responses = [
‘{“id”: 123, “name”: “Alice”}’, # 正常
‘{“id”: “456”, “name”: “Bob”}’, # ID 是字符串
‘{“id”: 789}’, # 缺少 name
‘{“id”: null, “name”: “Charlie”}’, # ID 是 null
‘{“name”: “David”}’, # 缺少 id
‘invalid json’, # 格式错误
]

def process_user_data(json_str):
try:
data = json.loads(json_str)
except json.JSONDecodeError:
return “Error: Invalid JSON format”

# — 处理数据结构不匹配 —

# 方法 1: 使用 .get() 提供默认值 (推荐)
user_id = data.get(‘id’, ‘N/A’) # 如果 ‘id’ 不存在,返回 ‘N/A’
user_name = data.get(‘name’, ‘Unknown’)

# 方法 2: 检查键是否存在
if ‘id’ not in data:
print(f”Warning: User data missing ‘id’ field. Data: {data}”)
# 决定是否继续处理或抛出异常
# return “Error: Missing ID”

# 方法 3: 类型检查和转换
if user_id is not None and not isinstance(user_id, int):
try:
user_id = int(user_id)
except (ValueError, TypeError):
print(f”Warning: Cannot convert user_id ‘{user_id}’ to int.”)
user_id = ‘Invalid’

return f”Processed User: ID={user_id}, Name={user_name}”

for i, response in enumerate(api_responses):
print(f”Response {i+1}: {process_user_data(response)}”)
输出:
Processed User: ID=123, Name=Alice
Processed User: ID=456, Name=Bob
Warning: User data missing ‘id’ field. Data: {‘id’: 789}
Processed User: ID=789, Name=Unknown
Warning: Cannot convert user_id ‘None’ to int.
Processed User: ID=Invalid, Name=Charlie
Warning: User data missing ‘id’ field. Data: {‘name’: ‘David’}
Processed User: ID=N/A, Name=David
Error: Invalid JSON format
关键策略:
.get(key, default)
: 总是使用字典的
.get()
方法来安全地访问键,避免
KeyError
。
in
操作符
: 在访问前检查键是否存在。
类型检查
: 使用
isinstance()
检查值的类型,并进行必要的转换或错误处理。
try-except
块
: 对于类型转换操作,使用
try-except
捕获
ValueError
或
TypeError
。
3.4 处理编码问题
JSON 字符串通常是 Unicode 编码。在 Python 3 中,
str
类型是 Unicode,这大大简化了处理。但在读取文件或网络数据时,可能会遇到编码问题。
最佳实践:
读取文件时,始终指定
encoding=’utf-8′
。
如果数据来源可能包含非 UTF-8 编码,需要进行检测和转换。
import json

# 模拟一个包含非 ASCII 字符的 JSON 字符串 (UTF-8)
json_bytes = ‘{“name”: “张三”, “city”: “北京”}’.encode(‘utf-8’)

# 正确解析 bytes
data = json.loads(json_bytes) # json.loads 可以直接接受 bytes
print(data)

# 如果数据是其他编码,例如 latin-1
json_latin_bytes = ‘{“name”: “José”}’.encode(‘latin-1’)
try:
# 尝试直接解析 latin-1 bytes (可能会失败或乱码,因为 json.loads 默认期望 utf-8)
data_latin = json.loads(json_latin_bytes)
print(data_latin)
except UnicodeDecodeError:
print(“Latin-1 bytes cannot be directly parsed as UTF-8”)

# 解决方案:先解码为字符串,再解析
decoded_str = json_latin_bytes.decode(‘latin-1’)
data_fixed = json.loads(decoded_str)
print(data_fixed)
3.5 验证 JSON 数据结构:使用 JSON Schema
对于复杂的、结构化的 JSON 数据,手动编写检查逻辑会非常繁琐且容易出错。
jsonschema
库允许你定义一个“模式”(Schema)来验证 JSON 数据。
安装 jsonschema:
pip install jsonschema
示例:验证用户注册数据
假设我们期望的数据结构是:
username
: 必须是字符串,长度 3-20
age
: 必须是整数,大于 18
email
: 必须是有效的邮箱格式
import json
import jsonschema
from jsonschema import validate

# 1. 定义 Schema
user_schema = {
“type”: “object”,
“properties”: {
“username”: {“type”: “string”, “minLength”: 3, “maxLength”: 20},
“age”: {“type”: “integer”, “minimum”: 18},
“email”: {“type”: “string”, “format”: “email”},
“tags”: {“type”: “array”, “items”: {“type”: “string”}} # 可选字段
},
“required”: [“username”, “age”, “email”], # 必填字段
“additionalProperties”: False # 不允许有 schema 之外的字段
}

# 2. 测试数据
test_cases = [
‘{“username”: “alice”, “age”: 25, “email”: “alice@example.com”}’, # 有效
‘{“username”: “al”, “age”: 25, “email”: “alice@example.com”}’, # 无效:username 太短
‘{“username”: “alice”, “age”: 17, “email”: “alice@example.com”}’, # 无效:age 太小
‘{“username”: “alice”, “age”: 25, “email”: “not-an-email”}’, # 无效:邮箱格式错误
‘{“username”: “alice”, “age”: 25}’, # 无效:缺少 email
‘{“username”: “alice”, “age”: 25, “email”: “alice@example.com”, “extra”: “field”}’ # 无效:多余字段
]

# 3. 验证函数
def validate_user(json_str):
try:
data = json.loads(json_str)
validate(instance=data, schema=user_schema)
return “Validation successful”
except json.JSONDecodeError as e:
return f”JSON Parse Error: {e}”
except jsonschema.exceptions.ValidationError as e:
return f”Schema Validation Error: {e.message}”

# 4. 运行验证
for i, case in enumerate(test_cases):
print(f”Case {i+1}: {validate_user(case)}”)
输出:
Case 1: Validation successful
Case 2: Schema Validation Error: ‘al’ is too short
Case 3: Schema Validation Error: 17 is less than the minimum of 18
Case 4: Schema Validation Error: ‘not-an-email’ is not a ’email’
Case 5: Schema Validation Error: ’email’ is a required property
Case 6: Schema Validation Error: Additional properties are not allowed (‘extra’ was unexpected)
使用
jsonschema
可以将数据验证逻辑与业务逻辑分离,使代码更清晰、更健壮。
4. 最佳实践总结
总是使用
try-except
: 将
json.loads()
放在
try
块中,捕获
json.JSONDecodeError
。
安全访问字典键
: 使用
data.get(‘key’, default_value)
而不是
data[‘key’]
。
类型检查与转换
: 在使用数据前,检查其类型是否符合预期,并进行安全转换。
处理大型数据
: 对于大文件,使用
ijson
进行流式解析;对于追求极致性能的场景,考虑
orjson
。
验证复杂结构
: 使用
jsonschema
库来定义和验证数据模式。
注意编码
: 始终明确处理字符编码,优先使用 UTF-8。
日志记录
: 当解析或验证失败时,记录详细的错误信息(包括原始数据片段),以便于调试。
通过遵循这些策略和实践,你可以编写出能够优雅地处理各种 JSON 数据和错误情况的 Python 代码,从而构建更加稳定和可靠的应用程序。