目录
一、简介
二、JSON 和 Python 的对应关系
三、核心函数
1. json.dumps():将 Python 对象 → JSON 字符串
2. json.loads():将 JSON 字符串 → Python 对象
3. json.dump():将 Python 对象 → JSON 文件
4. json.load():从 JSON 文件 → Python 对象
四、常见错误处理
1. JSON 解析错误
2. 类型不支持错误
五、总结
六、常用函数
1️⃣ json.dumps() - 序列化为字符串
2️⃣ json.loads() - 反序列化字符串
3️⃣ json.dump() - 写入JSON文件
4️⃣ json.load() - 读取JSON文件
⚙️ 关键参数详解
json.loads() 和 json.load() 注意点:
七、实际应用场景
JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,Python 内置的 json
库可以方便地将 Python对象 与 JSON格式数据 相互转换。
JSON 格式与 Python 数据类型的对应关系:
JSON对象
↔ Python字典(dict)
JSON数组
↔ Python列表(list)
或 元组(tuple)
JSON字符串
↔ Python字符串(str)
JSON数字
↔ Python整数(int)
或 浮点数(float)
JSON布尔值(true/false)
↔ Python布尔值(True/False)
JSON null
↔ Python None
json
库有 4 个核心函数:
json.dumps()
:将 Python 对象 → JSON 字符串import json
data = {
"name": "张三",
"age": 25,
"hobbies": ["读书", "跑步"]
}
json_str = json.dumps(data, ensure_ascii=False, indent=4)
print(json_str)
参数说明:
ensure_ascii=False
:允许输出非ASCII字符(如中文)
indent=4
:格式化缩进,提高可读性
json.loads()
:将 JSON 字符串 → Python 对象json_str = '{"name": "李四", "age": 30}'
python_dict = json.loads(json_str)
print(python_dict["name"]) # 输出:李四
json.dump()
:将 Python 对象 → JSON 文件data = {"key": "value"}
with open("data.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=4)
json.load()
:从 JSON 文件 → Python 对象with open("data.json", "r", encoding="utf-8") as f:
data = json.load(f)
print(data["key"]) # 输出:value
try:
data = json.loads('{"invalid": json}')
except json.JSONDecodeError as e:
print(f"解析错误:{e}")
确保所有数据均可被序列化,或通过 default
参数处理。
序列化(Python→JSON):dumps()
或 dump()
反序列化(JSON→Python):loads()
或 load()
处理中文时使用 ensure_ascii=False
复杂对象需自定义序列化逻辑
函数名 | 作用 | 输入类型 | 输出类型 | 典型场景 |
---|---|---|---|---|
json.dumps() |
Python对象 → JSON字符串 | 字典/列表等 | 字符串 | 将数据转为JSON发送给API |
json.loads() |
JSON字符串 → Python对象 | 字符串 | 字典/列表等 | 解析API返回的JSON数据 |
json.dump() |
Python对象 → JSON文件 | 字典/列表等 | 无(写入文件) | 保存配置到本地文件 |
json.load() |
JSON文件 → Python对象 | 文件对象 | 字典/列表等 | 读取本地配置文件 |
json.dumps()
- 序列化为字符串将 Python 对象转为格式化的 JSON 字符串
import json
data = {
"name": "张三",
"age": 30,
"is_student": False,
"hobbies": ["阅读", "编程"]
}
# 基础用法
json_str = json.dumps(data)
print(json_str) # 输出紧凑的JSON字符串(无缩进,中文会被转义)
# 优化参数用法
json_str_pretty = json.dumps(
data,
ensure_ascii=False, # 允许显示中文
indent=2, # 缩进2空格
sort_keys=True # 按键名排序
)
print(json_str_pretty)
输出结果:
{"name": "\u5f20\u4e09", "age": 30, "is_student": false, "hobbies": ["\u9605\u8bfb", "\u7f16\u7a0b"]}
{
"age": 30,
"hobbies": [
"阅读",
"编程"
],
"is_student": false,
"name": "张三"
}
json.loads()
- 反序列化字符串将 JSON 字符串解析为 Python 对象
json_str = '''
{
"name": "李四",
"scores": [95, 87, 92],
"metadata": {
"class": "A班",
"teacher": "王老师"
}
}
'''
# 解析JSON字符串
data = json.loads(json_str)
print(data["metadata"]["teacher"]) # 输出:王老师
print(data["scores"][1]) # 输出:87
json.dump()
- 写入JSON文件将 Python 对象直接保存到 JSON 文件
config = {
"language": "Python",
"version": 3.9,
"packages": ["numpy", "pandas"]
}
# 写入文件(自动处理文件操作)
with open("config.json", "w", encoding="utf-8") as f:
json.dump(
config,
f,
ensure_ascii=False, # 保持中文可读
indent=4 # 缩进4空格
)
生成的文件内容:
{
"language": "Python",
"version": 3.9,
"packages": [
"numpy",
"pandas"
]
}
json.load()
- 读取JSON文件从 JSON 文件直接加载为 Python 对象
# 读取文件
with open("config.json", "r", encoding="utf-8") as f:
loaded_config = json.load(f)
print(loaded_config["packages"]) # 输出:['numpy', 'pandas']
参数 | 作用 | 示例值 |
---|---|---|
ensure_ascii |
是否转义非ASCII字符(如中文) | False |
indent |
缩进空格数(美化输出) | 2 或 4 |
sort_keys |
是否按键名字母排序 | True /False |
separators |
控制分隔符样式 | (",", ": ") |
json.loads()
和 json.load()
注意点:如果 JSON 中有重复键名,后出现的键会覆盖前面的值
遇到非法 JSON 格式会抛出 JSONDecodeError
API 数据交互
# 发送请求时将字典转为JSON
import requests
data = {"query": "搜索内容"}
headers = {"Content-Type": "application/json"}
response = requests.post(url, data=json.dumps(data), headers=headers)
# 解析响应
result = json.loads(response.text)
配置文件管理
# 读取配置
with open("settings.json") as f:
settings = json.load(f)
# 修改后保存
settings["theme"] = "dark"
with open("settings.json", "w") as f:
json.dump(settings, f, indent=4)
数据持久化存储
# 保存用户数据
user_data = {"id": 123, "history": [...]}
with open("user_data.json", "w") as f:
json.dump(user_data, f)