首页 › Python 标准库 › json 数据处理

json 数据处理

JSON 是最常见的数据交换格式。json 模块负责 Python 对象和 JSON 文本之间的转换。

import json

data = {"name": "小明", "age": 20, "skills": ["Python", "SQL"]}

text = json.dumps(data, ensure_ascii=False, indent=2)
print(text)

obj = json.loads(text)
print(obj["skills"][0])     # Python

读写 JSON 文件

with open("config.json", "w", encoding="utf-8") as f:
    json.dump(data, f, ensure_ascii=False, indent=2)

with open("config.json", encoding="utf-8") as f:
    config = json.load(f)

类型对应关系

JSONPython
objectdict
arraylist
stringstr
numberint / float
true / falseTrue / False
nullNone

序列化自定义对象

datetime 等对象不能直接序列化,可以通过 default 参数指定转换方式:

from datetime import datetime
json.dumps({"t": datetime.now()}, default=str)

练习题

学完本节后,试着独立完成下面的练习,再展开参考答案对照。

练习 1 把一个包含中文和嵌套结构的字典转换为格式化的 JSON,再转回来并验证内容相同。

查看参考答案
import json
data = {"课程": "Python", "章节": [{"标题": "函数", "页数": 12}]}
text = json.dumps(data, ensure_ascii=False, indent=2)
print(text)
print(json.loads(text) == data)
参考输出:
{
  "课程": "Python",
  "章节": [
    {
      "标题": "函数",
      "页数": 12
    }
  ]
}
True