JSON
常用函数
函数
作用
import json
# Python 对象转 JSON 字符串
data = {"name": "Alice", "age": 20, "is_student": False}
json_str = json.dumps(data)
print(json_str)
# JSON 字符串转 Python 对象
parsed = json.loads(json_str)
print(parsed)import json
data = {"name": "Alice", "age": 20, "is_student": False}
# 写入 JSON 文件
with open("data.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
with open("data.json", "r", encoding="utf-8") as f:
json.load(f)常用参数说明
参数
说明
Python 与 JSON 类型映射
Python 类型
JSON 类型
自定义序列化(处理不支持的类型)
方法 1:使用default参数
default参数方法 2: 继承json.JSONEncoder
json.JSONEncoder常见错误与注意事项
性能建议
最后更新于