下面是关于 Python 中如何全面处理 JSON 的详细说明,包括模块介绍、数据类型映射、常用函数、文件操作、异常处理、进阶技巧等。
JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,常用于 API 和配置文件。
示例:
{
"name": "张三",
"age": 28,
"is_student": false,
"skills": ["Python", "Java"],
"address": {
"city": "北京",
"zipcode": "100000"
}
}
json
模块简介Python 提供内置模块 json
,支持 JSON 和 Python 对象之间的 序列化(encode) 和 反序列化(decode)。
import json
JSON 类型 | Python 类型 |
---|---|
object | dict |
array | list |
string | str |
number | int / float |
true / false | True / False |
null | None |
json.dumps()
— Python 对象 → JSON 字符串import json
data = {"name": "李雷", "age": 20}
json_str = json.dumps(data, ensure_ascii=False, indent=2)
print(json_str)
参数说明:
ensure_ascii=False
:中文不转义,默认是 True
(会变成 \uXXXX)indent=2
:格式化输出,2 表示缩进空格数sort_keys=True
:按键名排序输出json.loads()
— JSON 字符串 → Python 对象json_str = '{"name": "韩梅梅", "age": 22}'
data = json.loads(json_str)
print(data["name"]) # 韩梅梅
json.dump()
— Python 对象 → 写入 JSON 文件data = {"name": "Tom", "age": 18}
with open("user.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
json.load()
— 从 JSON 文件读取为 Python 对象with open("user.json", "r", encoding="utf-8") as f:
data = json.load(f)
print(data["name"])
处理不合法 JSON 字符串时要加异常保护:
try:
json_str = '{"name": "Error", "age": 30' # 缺少结尾大括号
data = json.loads(json_str)
except json.JSONDecodeError as e:
print("JSON 解析失败:", e)
json_str = '''
{
"user": {
"name": "张三",
"info": {
"age": 30,
"skills": ["Python", "Go"]
}
}
}
'''
data = json.loads(json_str)
print(data["user"]["info"]["skills"][0]) # Python
class User:
def __init__(self, name, age):
self.name = name
self.age = age
u = User("Lucy", 18)
json_str = json.dumps(u.__dict__, ensure_ascii=False)
print(json_str)
务必加上 encoding='utf-8'
,否则可能乱码。
with open("config.json", "r", encoding="utf-8") as f:
config = json.load(f)
config["debug"] = False
with open("config.json", "w", encoding="utf-8") as f:
json.dump(config, f, ensure_ascii=False, indent=2)
如果你有: