Python通过json模块实现JSON数据的序列化与反序列化,核心函数包括json.loads()、json.load()、json.dumps()和json.dump(),支持数据类型映射、文件读写及错误处理;对于大型JSON文件,推荐使用ijson库进行流式解析以降低内存占用;自定义对象可通过default函数或继承JSONEncoder/Decoder实现序列化与反序列化,确保复杂数据结构的完整转换。

Python处理JSON数据主要依赖其内置的
json
在Python中,处理JSON数据主要是围绕着
json
json.loads()
json.load()
json.dumps()
json.dump()
import json
# 示例1: 从JSON字符串解析到Python对象 (反序列化)
json_string = '{"name": "张三", "age": 30, "isStudent": false, "courses": ["Python", "Data Science"]}'
python_data = json.loads(json_string)
print(f"解析后的Python数据类型: {type(python_data)}")
print(f"解析后的Python数据: {python_data}")
print(f"访问姓名: {python_data['name']}")
# 示例2: 从Python对象生成JSON字符串 (序列化)
python_dict = {
"product": "Laptop",
"price": 1200.50,
"features": ["SSD", "16GB RAM"],
"available": True
}
json_output = json.dumps(python_dict, indent=4, ensure_ascii=False) # indent用于美化输出,ensure_ascii=False支持中文
print(f"\n序列化后的JSON字符串:\n{json_output}")
# 示例3: 处理JSON文件 (读写)
data_to_write = {
"city": "Beijing",
"population": 21000000,
"landmarks": ["Great Wall", "Forbidden City"]
}
file_path = "data.json"
# 写入JSON文件
with open(file_path, 'w', encoding='utf-8') as f:
json.dump(data_to_write, f, indent=4, ensure_ascii=False)
print(f"\n数据已写入 {file_path}")
# 从JSON文件读取
with open(file_path, 'r', encoding='utf-8') as f:
read_data = json.load(f)
print(f"从文件读取的数据: {read_data}")
# Python数据类型与JSON类型映射概览:
# Python | JSON
# ----------------|----------------
# dict | object
# list, tuple | array
# str | string
# int, float | number
# True | true
# False | false
# None | null在实际操作中,
json.dumps()
indent
ensure_ascii=False
\uXXXX
处理大型JSON文件,比如几百MB甚至几个GB的文件,直接使用
json.load()
立即学习“Python免费学习笔记(深入)”;
一种常见的优化方式是,如果JSON文件是一个包含大量独立JSON对象的列表,我们可以尝试逐行读取并解析。但这有个前提,就是文件中的每个JSON对象必须是独立且合法的,并且通常以换行符分隔。然而,更通用的解决方案是利用第三方库,比如
ijson
ijson
# 假设有一个名为 large_data.json 的大型文件,内容结构类似:
# [
# {"id": 1, "value": "abc"},
# {"id": 2, "value": "def"},
# ...
# ]
# 伪代码示例,需要安装 ijson: pip install ijson
# import ijson
#
# try:
# with open('large_data.json', 'rb') as f: # 注意,ijson通常需要以二进制模式打开文件
# # items(''), 'item'表示解析根数组下的每个元素
# # 如果根是一个对象,可以指定路径,如 items('data.items')
# for record in ijson.items(f, 'item'):
# # 在这里处理每个 record,比如写入数据库、聚合数据等
# print(f"处理记录: {record['id']}")
# # 模拟一些处理
# if record['id'] > 5:
# break # 提前退出,节省资源
# except FileNotFoundError:
# print("large_data.json 文件未找到。")
# except Exception as e:
# print(f"处理 large_data.json 时发生错误: {e}")
# 另一种思路是,如果JSON结构允许,可以尝试分块读取文件内容,
# 但这通常需要对JSON结构有深入了解,确保分块不会截断有效的JSON对象。
# 比如,如果文件是多个独立JSON对象用换行符分隔,则可以逐行读取。
# with open('multiple_objects.json', 'r', encoding='utf-8') as f:
# for line in f:
# if line.strip(): # 确保不是空行
# try:
# obj = json.loads(line)
# print(f"处理独立对象: {obj}")
# except json.JSONDecodeError as e:
# print(f"解析行失败: {line.strip()} - {e}")ijson
ijson
Easily find JSON paths within JSON objects using our intuitive Json Path Finder
30
解析JSON数据并非总是一帆风顺,尤其是在从外部源获取数据时,可能会遇到格式不规范、数据缺失或类型不匹配等问题。这时候,Python的错误处理机制就显得尤为重要了。最常见的错误是
json.JSONDecodeError
import json
# 错误示例1: 无效的JSON格式
invalid_json_string = '{"name": "Alice", "age": 25,' # 缺少闭合括号
try:
data = json.loads(invalid_json_string)
print(data)
except json.JSONDecodeError as e:
print(f"JSON解析错误: {e}")
print(f"错误发生在位置: {e.pos}, 行: {e.lineno}, 列: {e.colno}")
# 错误示例2: 数据缺失 (KeyError)
valid_json_string = '{"user_id": 123, "username": "bob"}'
try:
user_data = json.loads(valid_json_string)
# 尝试访问一个不存在的键
email = user_data['email']
print(f"用户邮箱: {email}")
except KeyError as e:
print(f"数据访问错误: 键 '{e}' 不存在。")
# 可以提供默认值或记录日志
email = "unknown@example.com"
print(f"使用默认邮箱: {email}")
# 错误示例3: 数据类型不匹配或预期值不符
data_with_wrong_type = '{"id": "abc", "value": "123"}'
try:
item = json.loads(data_with_wrong_type)
# 假设我们期望 id 是整数
item_id = int(item['id'])
print(f"处理后的ID: {item_id}")
except ValueError as e:
print(f"数据类型转换错误: {e}")
except TypeError as e:
print(f"数据类型错误: {e}")处理这些错误的关键在于使用
try-except
json.JSONDecodeError
KeyError
if 'key' in dict:
ValueError
TypeError
int()
float()
将Python的内置类型(如字典、列表、字符串、数字等)序列化为JSON是
json
User
json.dumps(user_object)
TypeError: Object of type User is not JSON serializable
json
核心思路是告诉
json
default
json.dumps()
json
json.loads()
object_hook
json
import json
class User:
def __init__(self, name, age, email):
self.name = name
self.age = age
self.email = email
def __repr__(self):
return f"User(name='{self.name}', age={self.age}, email='{self.email}')"
# 序列化自定义对象
def user_encoder(obj):
if isinstance(obj, User):
return {
'__type__': 'User', # 标记这是一个User对象,方便反序列化
'name': obj.name,
'age': obj.age,
'email': obj.email
}
raise TypeError(f"Object of type {obj.__class__.__name__} is not JSON serializable")
# 创建一个User实例
user1 = User("李华", 28, "lihua@example.com")
# 使用自定义编码器序列化
json_user = json.dumps(user1, default=user_encoder, indent=4, ensure_ascii=False)
print(f"序列化后的User对象:\n{json_user}")
# 反序列化回自定义对象
def user_decoder(dct):
if '__type__' in dct and dct['__type__'] == 'User':
return User(dct['name'], dct['age'], dct['email'])
return dct # 如果不是User对象,原样返回字典
# 使用自定义解码器反序列化
decoded_user = json.loads(json_user, object_hook=user_decoder)
print(f"\n反序列化后的对象: {decoded_user}")
print(f"反序列化后的对象类型: {type(decoded_user)}")
# 另一种更面向对象的方法是继承json.JSONEncoder和json.JSONDecoder
class UserEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, User):
return {
'__type__': 'User',
'name': obj.name,
'age': obj.age,
'email': obj.email
}
return json.JSONEncoder.default(self, obj) # 让基类处理其他类型
# 使用自定义Encoder
json_user_with_class = UserEncoder(indent=4, ensure_ascii=False).encode(user1)
print(f"\n使用自定义Encoder序列化:\n{json_user_with_class}")我个人更倾向于使用继承
json.JSONEncoder
json.JSONDecoder
default
User
__type__
object_hook
User
以上就是python如何处理json数据_python JSON数据解析与生成指南的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号