Skip to content

L5-5 · JSON 读写:配置和数据的通用语言 ​

一句话人话:JSON 是"程序之间传话的万能格式"——Python 字典的样子、纯文本的身体;json.dumps 把字典写成字符串,json.loads 把字符串读回字典,一写一读往返无损。

定义 ​

python
import json

text = json.dumps(字典, ensure_ascii=False, indent=2)   # 序列化:对象 → 字符串
d = json.loads(text)                                     # 反序列化:字符串 → 对象
d = json.loads(Path("配置.json").read_text(encoding="utf-8"))  # 直接读文件
Path("out.json").write_text(json.dumps(d, ensure_ascii=False, indent=2), encoding="utf-8")

ensure_ascii=False:中文原样输出(不加会变成 \u4f60 天书);indent=2:人类可读的缩进。

我们项目里的例子 ​

例 1:读题目定义——批改脚本(真实代码):

python
specs = [json.loads(p.read_text(encoding="utf-8")) for p in sorted(QUIZ_DIR.glob("*.json"))]

练习/题目/hello-python.json 文件里的内容 → 变成 spec 字典 → spec["slug"]、spec["expect_output"] 随便取——你的每道练习题都是一个 JSON 文件。

例 2:写成绩单前置数据——机器人更新成绩单前先构建结果(真实逻辑):

python
row = {"slug": slug, "title": spec["title"], "lang": lang, "status": ..., "note": ...}

这样的字典列表最终变成成绩单的表格行——数据在"字典(内存)↔ JSON/Markdown(磁盘)"之间往返。

例 3:予安 API 的响应就是 JSON(真实输出,抓包卡抓到的):

json
{"code":400,"message":"手机号或密码不对,再试试","data":null}

前端 axios 收到后自动 loads 成 JS 对象——JSON 是前后端之间的通用语,Python 和 JS 读写它的语法几乎一样。

对应关系速查 ​

PythonJSON备注
dictobject {}
listarray []
strstring
int / floatnumber
True / False / Nonetrue / false / null大小写变化!

动手 ​

Python序列化往返实验

自测 ​

相关知识点 ​

下一课 → L6-1 模块与包