在现代软件开发中,JSON(JavaScript Object Notation) 已成为最流行的数据交换格式之一。Python 提供了内置的 json
模块,使得我们可以方便地解析 JSON 数据(读取)和生成 JSON 数据(写入)。无论是 Web API 交互、配置文件存储,还是数据序列化,json
模块都是不可或缺的工具。本文将详细介绍 json
模块的读取、写入、格式化、编码解码等操作,并结合实际案例展示其应用。
1. JSON 与 Python 数据类型的映射关系
Python 的 json
模块可以在 Python 基本数据类型和 JSON 数据类型之间相互转换,映射关系如下:
Python 类型 | JSON 类型 | 示例 |
---|---|---|
dict | object | {"name": "Alice", "age": 25} |
list / tuple | array | ["apple", "banana", "cherry"] |
str | string | "hello" |
int / float | number | 42 , 3.14 |
bool | true / false | true , false |
None | null | null |
2. 读取 JSON 数据
Python 可以从字符串或文件中读取 JSON 数据。
2.1 从 JSON 字符串解析
import json
json_str = '{"name": "Alice", "age": 25, "city": "New York"}'
# 将 JSON 字符串转换为 Python 字典
data = json.loads(json_str)
print(data["name"]) # 输出: Alice
print(type(data)) # 输出: <class 'dict'>
📌 json.loads()
作用:
- 输入:JSON 格式的字符串。
- 输出:转换为 Python
dict
对象。
2.2 从 JSON 文件读取
假设有一个 data.json
文件:
{
"name": "Bob",
"age": 30,
"skills": ["Python", "Java", "C++"]
}
使用 json.load()
读取文件:
with open("data.json", "r", encoding="utf-8") as file:
data = json.load(file)
print(data["name"]) # 输出: Bob
print(data["skills"]) # 输出: ['Python', 'Java', 'C++']
📌 json.load()
作用:
- 输入:JSON 文件对象。
- 输出:Python
dict
对象。
3. 写入 JSON 数据
Python 可以将数据写入字符串或文件。
3.1 将 Python 对象转换为 JSON 字符串
import json
data = {
"name": "Charlie",
"age": 28,
"city": "San Francisco"
}
# 将 Python 字典转换为 JSON 字符串
json_str = json.dumps(data)
print(json_str)
print(type(json_str)) # 输出: <class 'str'>
📌 json.dumps()
作用:
- 输入:Python
dict
、list
、str
等。 - 输出:JSON 格式的字符串。
3.2 将 Python 对象写入 JSON 文件
import json
data = {
"name": "David",
"age": 35,
"languages": ["Python", "Go", "Rust"]
}
# 写入 JSON 文件
with open("output.json", "w", encoding="utf-8") as file:
json.dump(data, file)
print("数据已写入 output.json")
📌 json.dump()
作用:
- 输入:Python
dict
(或其他可序列化对象)。 - 输出:写入 JSON 文件。
4. JSON 格式化输出(缩进、排序)
默认情况下,JSON 生成的字符串是紧凑的,不易阅读:
data = {"name": "Eve", "age": 26, "city": "Paris"}
json_str = json.dumps(data)
print(json_str) # 输出: {"name": "Eve", "age": 26, "city": "Paris"}
为了更清晰地输出 JSON,可以使用 indent
参数:
json_str = json.dumps(data, indent=4)
print(json_str)
📌 输出(格式化 JSON):
{
"name": "Eve",
"age": 26,
"city": "Paris"
}
如果希望按键名排序:
json_str = json.dumps(data, indent=4, sort_keys=True)
print(json_str)
📌 输出(按键排序):
{
"age": 26,
"city": "Paris",
"name": "Eve"
}
5. 处理 JSON 编码与解码(对象序列化)
如果 JSON 数据包含自定义对象,默认 json.dumps()
无法处理:
import json
from datetime import datetime
data = {"name": "Alice", "time": datetime.now()}
# 会报错:Object of type datetime is not JSON serializable
json_str = json.dumps(data)
可以使用 default
参数,将 datetime
对象转换为字符串:
def json_serial(obj):
if isinstance(obj, datetime):
return obj.isoformat() # 转换为 ISO 8601 时间格式
raise TypeError("Type not serializable")
json_str = json.dumps(data, default=json_serial, indent=4)
print(json_str)
📌 示例输出:
{
"name": "Alice",
"time": "2024-02-04T14:00:00.123456"
}
6. 处理 JSON 解析错误
解析 JSON 时,可能会遇到格式错误:
import json
invalid_json = '{"name": "Tom", "age": 30,}' # 末尾多了逗号
try:
data = json.loads(invalid_json)
except json.JSONDecodeError as e:
print(f"JSON 解析错误: {e}")
📌 输出:
JSON 解析错误: Expecting property name enclosed in double quotes
7. JSON 读写的最佳实践
✅ 读取 JSON 时使用 try-except
捕获异常
try:
with open("config.json", "r", encoding="utf-8") as file:
config = json.load(file)
except (FileNotFoundError, json.JSONDecodeError) as e:
print(f"错误: {e}")
✅ 写入 JSON 时使用 indent=4
让数据更易读
json.dump(data, file, indent=4)
✅ 处理非标准数据类型时,使用 default
进行序列化
json.dumps(data, default=json_serial)
8. 结论
操作 | 方法 |
---|---|
从字符串读取 JSON | json.loads(json_str) |
从文件读取 JSON | json.load(file) |
将 Python 对象转换为 JSON 字符串 | json.dumps(obj) |
将 Python 对象写入 JSON 文件 | json.dump(obj, file) |
格式化 JSON(缩进) | json.dumps(obj, indent=4) |
解析错误处理 | json.JSONDecodeError |
处理非标准数据类型 | default=json_serial |
Python 的 json
模块提供了强大且易用的 JSON 处理能力,合理使用这些方法,可以让你的代码更加高效、可维护!🚀
📌 有什么问题和经验想分享?欢迎在评论区交流、点赞、收藏、关注! 🎯