Python JSON 模块入门
JSON 是常用的数据交换格式,Python 内置 json 模块支持编码和解码。
1. 基本操作
import json
# Python 对象转 JSON 字符串
data = {"name": "Alice", "age": 25}
json_str = json.dumps(data)
print(json_str) # {"name": "Alice", "age": 25}
# JSON 字符串转 Python 对象
parsed = json.loads(json_str)
print(parsed) # {'name': 'Alice', 'age': 25}
2. 文件操作
# 写入 JSON 文件
with open("data.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
# 读取 JSON 文件
with open("data.json", "r", encoding="utf-8") as f:
data = json.load(f)
3. 美化输出
data = {"name": "Alice", "skills": ["Python", "Go"]}
# 缩进格式化
print(json.dumps(data, indent=2))
print(json.dumps(data, sort_keys=True)) # 按键排序
4. 处理日期
import json
from datetime import datetime
class DateEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
return super().default(obj)
data = {"time": datetime.now()}
print(json.dumps(data, cls=DateEncoder))
5. 处理自定义对象
def custom_decoder(d):
return Person(d["name"], d["age"])
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def from_dict(cls, d):
return cls(d["name"], d["age"])
def to_dict(self):
return {"name": self.name, "age": self.age}
# 注册解析器
json.loads(json_str, object_hook=Person.from_dict)
JSON 是 Web API 数据交换的核心格式。