04
文件操作与简单模块化 · 2 / 4
4.2 JSON 文件:推理配置的标准格式
💡 模型配置、sampling 参数、prompt 模板几乎都是 JSON
4.2 JSON 文件
四个核心函数
import json
cfg = {"model": "qwen2.5-7b", "temperature": 0.7}
# 对象 → 字符串
s = json.dumps(cfg)
print(s) # {"model": "qwen2.5-7b", "temperature": 0.7}
# 字符串 → 对象
obj = json.loads(s)
print(obj["model"]) # qwen2.5-7b
# 对象 → 文件
with open("cfg.json", "w") as f:
json.dump(cfg, f, indent=2)
# 文件 → 对象
with open("cfg.json") as f:
cfg2 = json.load(f)
口诀:带 s 的处理字符串,不带 s 的处理文件。
示范
import json
cfg = {"model": "qwen2.5-7b", "temperature": 0.7, "max_tokens": 512}
with open("cfg.json", "w", encoding="utf-8") as f:
json.dump(cfg, f, indent=2, ensure_ascii=False)
with open("cfg.json", "r", encoding="utf-8") as f:
loaded = json.load(f)
print(loaded["model"])
✍️ 练习
写代码:
- 定义
cfg = {"model": "qwen2.5-7b", "sampling": {"temperature": 0.7, "top_p": 0.9}, "max_tokens": 512} - 把它用
json.dump写到cfg.json,带indent=2和ensure_ascii=False - 再用
json.load读出来,赋值给cfg2 - 打印
cfg2["sampling"]["temperature"]
写完后可以把生成的 cfg.json 打开看看,会发现缩进很整齐。
💡 思路提示
点开看提示
indent=2让输出有 2 空格缩进,方便人看ensure_ascii=False让中文不被转成\uXXXXjson.load直接返回 dict,不需要再json.loads
✅ 参考解法
写不出来再打开
import json
cfg = {"model": "qwen2.5-7b", "sampling": {"temperature": 0.7, "top_p": 0.9}, "max_tokens": 512}
with open("cfg.json", "w", encoding="utf-8") as f:
json.dump(cfg, f, indent=2, ensure_ascii=False)
with open("cfg.json", "r", encoding="utf-8") as f:
cfg2 = json.load(f)
print(cfg2["sampling"]["temperature"])
🔍 进阶思考
如果 JSON 里有注释(// xxx),标准 json 模块会报错。生产里有时用 YAML 或 TOML 作为配置格式。
import yaml # pip install pyyaml
import tomllib # Python 3.11+ 内置