Python 中的 JSON 处理
JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成。Python 提供了内置的 json 模块,用于处理 JSON 数据。通过 json 模块,你可以将 Python 对象转换为 JSON 字符串(序列化),以及将 JSON 字符串转换为 Python 对象(反序列化)。
基本概念
- 序列化(Serialization):将 Python 对象转换为 JSON 字符串。
- 反序列化(Deserialization):将 JSON 字符串转换为 Python 对象。
- Python 对象与 JSON 数据的对应关系:
dict对应 JSON 对象({})list和tuple对应 JSON 数组([])str对应 JSON 字符串("")int、float和bool对应 JSON 数字和布尔值None对应 JSONnull
示例讲解
让我们通过一些具体的例子来理解 json 模块的用法。
示例1:序列化 Python 对象为 JSON 字符串
import json
# Python 对象
data = {
"name": "Alice",
"age": 30,
"is_student": False,
"courses": ["Math", "Science"],
"address": {
"street": "123 Main St",
"city": "Anytown"
}
}
# 序列化为 JSON 字符串
json_str = json.dumps(data)
print(json_str)
在这个例子中,我们使用 json.dumps 方法将一个 Python 字典对象序列化为 JSON 字符串。
示例2:反序列化 JSON 字符串为 Python 对象
import json
# JSON 字符串
json_str = '{"name": "Alice", "age": 30, "is_student": false, "courses": ["Math", "Science"], "address": {"street": "123 Main St", "city": "Anytown"}}'
# 反序列化为 Python 对象
data = json.loads(json_str)
print(data)
在这个例子中,我们使用 json.loads 方法将一个 JSON 字符串反序列化为 Python 字典对象。
示例3:处理 JSON 文件
你可以使用 json 模块来读取和写入 JSON 文件。
import json
# 写入 JSON 文件
data = {
"name": "Alice",
"age": 30,
"is_student": False,
"courses": ["Math", "Science"],
"address": {
"street": "123 Main St",
"city": "Anytown"
}
}
with open('data.json', 'w') as f:
json.dump(data, f)
# 读取 JSON 文件
with open('data.json', 'r') as f:
data = json.load(f)
print(data)
在这个例子中,我们使用 json.dump 方法将 Python 对象写入 JSON 文件,并使用 json.load 方法从 JSON 文件中读取 Python 对象。
拓展内容
json 模块还提供了一些高级功能,例如:
- 自定义序列化和反序列化:通过
default参数和object_hook参数来自定义序列化和反序列化的行为。 - 排序和缩进:通过
sort_keys和indent参数来控制 JSON 字符串的格式。
下面是一个自定义序列化和反序列化的示例:
import json
# 自定义序列化
def custom_serializer(obj):
if isinstance(obj, complex):
return {"__complex__": True, "real": obj.real, "imag": obj.imag}
raise TypeError(f"Object of type {obj.__class__.__name__} is not JSON serializable")
# 自定义反序列化
def custom_deserializer(dct):
if "__complex__" in dct:
return complex(dct["real"], dct["imag"])
return dct
# 使用自定义序列化和反序列化
data = {
"name": "Alice",
"age": 30,
"is_student": False,
"courses": ["Math", "Science"],
"address": {
"street": "123 Main St",
"city": "Anytown"
},
"complex_number": complex(3, 4)
}
# 序列化为 JSON 字符串
json_str = json.dumps(data, default=custom_serializer)
print(json_str)
# 反序列化为 Python 对象
data = json.loads(json_str, object_hook=custom_deserializer)
print(data)
在这个例子中,我们通过 default 参数和 object_hook 参数自定义了序列化和反序列化的行为,使得 complex 类型的对象可以被正确处理。
775

被折叠的 条评论
为什么被折叠?



