Python怎么处理JSON文件:从基础到实战全解析
在数据交换和存储领域,JSON(JavaScript Object Notation)因其轻量级、易读性和与语言无关的特性,已成为前后端通信、配置文件存储、API数据交互的主流格式,Python作为一门功能强大的编程语言,内置了对JSON的完美支持,本文将从JSON文件的基础读写、数据转换、异常处理到实战应用,全面讲解Python如何高效处理JSON文件。
Python处理JSON的核心模块:json
Python标准库提供了json模块,专门用于JSON数据的编码(Python对象→JSON字符串/文件)和解码(JSON字符串/文件→Python对象),无需安装,直接通过import json即可使用。
JSON与Python对象的对应关系
理解JSON数据类型与Python类型的映射,是处理JSON的基础,以下是核心对应关系:
| JSON类型 | Python类型 |
|---|---|
| object(对象) | dict(字典) |
| array(数组) | list(列表) |
| string(字符串) | str(字符串) |
| number(数字) | int/float(整数/浮点数) |
| true/false | True/False(布尔值) |
| null | None(空值) |
读取JSON文件:json.load()与json.loads()
读取JSON文件的核心是将JSON数据转换为Python对象,主要通过两个函数实现:
从文件读取:json.load(file_object)
适用于直接从.json文件或已打开的文件对象读取数据。
示例:读取本地JSON文件
import json
# 假设存在 data.json 文件,内容如下:
# {
# "name": "张三",
# "age": 25,
# "hobbies": ["阅读", "编程"],
# "is_student": false
# }
# 打开文件并读取
with open('data.json', 'r', encoding='utf-8') as f:
data = json.load(f) # 将JSON文件转换为Python字典
# 访问数据
print(data['name']) # 输出: 张三
print(data['hobbies']) # 输出: ['阅读', '编程']
注意:文件需以utf-8编码打开(默认),避免中文乱码。
从字符串读取:json.loads(json_str)
适用于处理JSON格式的字符串(如API返回的响应数据)。
示例:解析JSON字符串
import json
json_str = '{"name": "李四", "age": 30, "city": "北京"}'
data = json.loads(json_str) # 将JSON字符串转换为Python字典
print(data['city']) # 输出: 北京
写入JSON文件:json.dump()与json.dumps()
将Python对象保存为JSON文件,核心是json.dump()和json.dumps():
写入文件:json.dump(obj, file_object, **kwargs)
将Python对象序列化为JSON格式并写入文件。
示例:将字典保存为JSON文件
import json
data = {
"name": "王五",
"age": 28,
"skills": ["Python", "数据分析"],
"is_employed": True
}
# 写入JSON文件,ensure_ascii=False确保中文正常显示,indent=4格式化输出
with open('output.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=4)
# 生成的 output.json 内容:
# {
# "name": "王五",
# "age": 28,
# "skills": [
# "Python",
# "数据分析"
# ],
# "is_employed": true
# }
参数说明:
ensure_ascii=False:允许非ASCII字符(如中文)直接输出,避免转义为\u格式。indent=4:指定缩进空格数,使JSON文件格式化,可读性更强。
转换为字符串:json.dumps(obj, **kwargs)
将Python对象序列化为JSON格式字符串,适用于网络传输或日志记录。
示例:将字典转为JSON字符串
import json
data = {"id": 1, "message": "操作成功"}
json_str = json.dumps(data, ensure_ascii=False, indent=2)
print(json_str)
# 输出:
# {
# "id": 1,
# "message": "操作成功"
# }
异常处理:避免JSON解析崩溃
处理JSON时,常见异常包括文件不存在、JSON格式错误(如缺少引号、括号不匹配等),需通过try-except捕获并处理。
示例:处理JSON文件读取异常
import json
try:
with open('invalid.json', 'r', encoding='utf-8') as f:
data = json.load(f)
except FileNotFoundError:
print("错误:文件不存在!")
except json.JSONDecodeError:
print("错误:JSON格式不正确!")
except Exception as e:
print(f"未知错误:{e}")
json.JSONDecodeError:当JSON字符串格式无效时触发(如{"name": "张三", age: 25}中age缺少引号)。
实战案例:处理复杂JSON数据
假设有一个包含嵌套结构的JSON文件users.json,存储用户信息,需提取并处理数据:
[
{
"id": 1,
"name": "Alice",
"profile": {
"age": 24,
"city": "上海"
},
"scores": [85, 90, 78]
},
{
"id": 2,
"name": "Bob",
"profile": {
"age": 30,
"city": "深圳"
},
"scores": [92, 88, 95]
}
]
需求:提取所有用户的姓名和城市,并计算平均分。
import json
# 读取JSON文件
with open('users.json', 'r', encoding='utf-8') as f:
users = json.load(f) # 此时users是列表,元素为字典
# 处理数据
for user in users:
name = user['name']
city = user['profile']['city']
avg_score = sum(user['scores']) / len(user['scores'])
print(f"姓名: {name}, 城市: {city}, 平均分: {avg_score:.1f}")
输出:
姓名: Alice, 城市: 上海, 平均分: 84.3
姓名: Bob, 城市: 深圳, 平均分: 91.7
进阶技巧
处理自定义对象(非字典/列表)
若需将Python自定义类对象转为JSON,可通过default参数指定序列化方法:
import json
class User:
def __init__(self, name, age):
self.name = name
self.age = age
# 自定义序列化函数
def user_to_dict(user):
return {'name': user.name, 'age': user.age}
user = User("Charlie", 35)
json_str = json.dumps(user, default=user_to_dict)
print(json_str) # 输出: {"name": "Charlie", "age": 35}
大文件流式处理
对于超大JSON文件(如GB级),可用ijson库(需安装:pip install ijson)逐块读取,避免内存溢出:
import ijson
with open('large_file.json', 'rb') as f:
for item in ijson.items(f, 'item'): # 假设JSON是数组,逐项读取
print(item) # 处理每个JSON对象
Python通过json模块提供了简单高效的JSON处理能力:
- 读取:
json.load()(文件)→json.loads()(字符串); - 写入:
json.dump()(文件)→json.dumps()(字符串); - 关键点:注意JSON与Python类型的映射、异常处理、中文编码(
ensure_ascii=False)。
这些方法,无论是处理配置文件、解析API响应,还是处理复杂数据结构,都能游刃有余。



还没有评论,来说两句吧...