在 Python 中,将数据转换为 JSON 格式非常简单,可以使用内置的 json 模块。json 模块提供了 json.dumps() 和 json.dump() 方法,用于将 Python 对象(如字典、列表、字符串等)转换为 JSON 字符串或写入文件。
一、Python 数据的 JSON 格式序列化
1. 使用 json.dumps() 将 Python 对象转换为 JSON 字符串
json.dumps() 方法将 Python 对象转换为 JSON 格式的字符串。
示例代码:
import json
# Python 字典
data = {
"name": "John",
"age": 30,
"is_student": False,
"courses": ["Math", "Science"],
"address": {
"city": "New York",
"zipcode": "10001"
}
}
# 将 Python 对象转换为 JSON 字符串
json_string = json.dumps(data, indent=4) # indent 参数用于美化输出,缩进 4 个空格
print(json_string)
输出:
{
"name": "John",
"age": 30,
"is_student": false,
"courses": [
"Math",
"Science"
],
"address": {
"city": "New York",
"zipcode": "10001"
}
}
2. 使用 json.dump() 将 Python 对象写入 JSON 文件
json.dump() 方法将 Python 对象直接写入文件。
示例代码:
import json
# Python 字典
data = {
"name": "John",
"age": 30,
"is_student": False,
"courses": ["Math", "Science"],
"address": {
"city": "New York",
"zipcode": "10001"
}
}
# 将 Python 对象写入 JSON 文件
with open("data.json", "w") as json_file:
json.dump(data, json_file, indent=4) # indent 参数用于美化输出
文件内容(data.json):
{
"name": "John",
"age": 30,
"is_student": false,
"courses": [
"Math",
"Science"
],
"address": {
"city": "New York",
"zipcode": "10001"
}
}
3. 处理不支持的数据类型
默认情况下,json 模块只能序列化以下 Python 数据类型:
- 字典
- 列表
- 字符串
- 整数
- 浮点数
- 布尔值
- None
如果需要序列化其他数据类型(如日期、自定义对象等),可以通过 default 参数指定一个转换函数。
示例代码:
import json
from datetime import datetime
# 自定义对象
class User:
def __init__(self, name, age):
self.name = name
self.age = age
# 自定义转换函数
def custom_serializer(obj):
if isinstance(obj, datetime):
return obj.isoformat() # 将 datetime 转换为字符串
elif isinstance(obj, User):
return {"name": obj.name, "age": obj.age} # 将 User 对象转换为字典
raise TypeError(f"Type {type(obj)} not serializable")
# 数据包含自定义对象和日期
data = {
"user": User("John", 30),
"created_at": datetime.now()
}
# 使用 default 参数处理不支持的类型
json_string = json.dumps(data, default=custom_serializer, indent=4)
print(json_string)
输出:
{
"user": {
"name": "John",
"age": 30
},
"created_at": "2023-10-05T12:34:56.789012"
}
4. 其他常用参数
- indent:指定缩进空格数,用于美化输出。
- sort_keys:是否按键名排序(默认为 False)。
- ensure_ascii:是否确保输出为 ASCII 字符(默认为 True,设置为 False 可以输出非 ASCII 字符)。
示例:
json_string = json.dumps(data, indent=4, sort_keys=True, ensure_ascii=False)
总结
- 使用 json.dumps() 将 Python 对象转换为 JSON 字符串。
- 使用 json.dump() 将 Python 对象写入 JSON 文件。
- 通过 default 参数处理不支持的数据类型。
- 使用 indent、sort_keys 等参数控制输出格式。
JSON 是 Web 开发中常用的数据交换格式,Python 的 json 模块提供了简单易用的工具来处理 JSON 数据。
二、Python 的 JSON 字符串反序列化
在 Python 中,将 JSON 字符串反序列化为 Python 对象(如字典、列表等)也非常简单,可以使用内置的 json 模块。json 模块提供了 json.loads() 和 json.load() 方法,用于将 JSON 字符串或文件内容转换为 Python 对象。
1. 使用 json.loads() 将 JSON 字符串转换为 Python 对象
json.loads() 方法将 JSON 格式的字符串转换为 Python 对象(通常是字典或列表)。
示例代码:
import json
# JSON 字符串
json_string = '''
{
"name": "John",
"age": 30,
"is_student": false,
"courses": ["Math", "Science"],
"address": {
"city": "New York",
"zipcode": "10001"
}
}
'''
# 将 JSON 字符串转换为 Python 对象
data = json.loads(json_string)
print(data)
print(type(data)) # 输出
输出:
{
'name': 'John',
'age': 30,
'is_student': False,
'courses': ['Math', 'Science'],
'address': {
'city': 'New York',
'zipcode': '10001'
}
}
2. 使用 json.load() 从 JSON 文件读取并转换为 Python 对象
json.load() 方法从文件中读取 JSON 数据并转换为 Python 对象。
示例代码:
假设有一个 data.json 文件,内容如下:
{
"name": "John",
"age": 30,
"is_student": false,
"courses": ["Math", "Science"],
"address": {
"city": "New York",
"zipcode": "10001"
}
}
读取并解析文件:
import json
# 从 JSON 文件中读取并转换为 Python 对象
with open("data.json", "r") as json_file:
data = json.load(json_file)
print(data)
print(type(data)) # 输出
输出:
{
'name': 'John',
'age': 30,
'is_student': False,
'courses': ['Math', 'Science'],
'address': {
'city': 'New York',
'zipcode': '10001'
}
}
3. 处理复杂数据类型
默认情况下,json 模块会将 JSON 数据转换为以下 Python 数据类型:
- JSON 对象 → Python 字典
- JSON 数组 → Python 列表
- JSON 字符串 → Python 字符串
- JSON 数字 → Python 整数或浮点数
- JSON true/false → Python True/False
- JSON null → Python None
如果需要将 JSON 数据转换为自定义对象,可以使用 object_hook 参数。
示例代码:
import json
# JSON 字符串
json_string = '''
{
"name": "John",
"age": 30,
"is_student": false,
"address": {
"city": "New York",
"zipcode": "10001"
}
}
'''
# 自定义类
class User:
def __init__(self, name, age, is_student, address):
self.name = name
self.age = age
self.is_student = is_student
self.address = address
def __repr__(self):
return f"User(name={self.name}, age={self.age}, is_student={self.is_student}, address={self.address})"
# 自定义转换函数
def custom_deserializer(dct):
if "name" in dct and "age" in dct: # 判断是否为 User 对象
return User(dct["name"], dct["age"], dct["is_student"], dct["address"])
return dct
# 使用 object_hook 参数处理自定义对象
data = json.loads(json_string, object_hook=custom_deserializer)
print(data)
输出:
User(name=John, age=30, is_student=False, address={'city': 'New York', 'zipcode': '10001'})
4. 其他注意事项
- JSON 字符串格式必须正确:如果 JSON 字符串格式不正确(例如缺少引号、括号不匹配等),会抛出 json.JSONDecodeError 异常。
- 处理日期和时间:JSON 本身不支持日期和时间类型,通常需要将日期时间转换为字符串后再反序列化。
示例:处理日期时间
import json
from datetime import datetime
# JSON 字符串
json_string = '''
{
"event": "Conference",
"date": "2023-10-05T12:34:56"
}
'''
# 自定义转换函数
def custom_deserializer(dct):
if "date" in dct:
dct["date"] = datetime.fromisoformat(dct["date"]) # 将字符串转换为 datetime 对象
return dct
# 使用 object_hook 参数处理日期时间
data = json.loads(json_string, object_hook=custom_deserializer)
print(data)
输出:
{
'event': 'Conference',
'date': datetime.datetime(2023, 10, 5, 12, 34, 56)
}
总结
- 使用 json.loads() 将 JSON 字符串转换为 Python 对象。
- 使用 json.load() 从 JSON 文件读取并转换为 Python 对象。
- 使用 object_hook 参数处理自定义对象或复杂数据类型。
- JSON 是 Web 开发中常用的数据交换格式,Python 的 json 模块提供了简单易用的工具来处理 JSON 数据。
好了,此文足已能让你无忧于 Python 数据的 JSON 格式序列化及反序列化了。
爱学习的小伙伴,关注不迷路哟~
python