如何设计 JSON Schema 验证技能配置,并在加载时报出行列号?

解读

在 Pygame 项目里,“技能配置”通常指 JSON 文件里定义的冷却时间、动画帧、伤害值、音效路径等字段。策划或关卡同学随时改表,程序要在启动阶段把错误一次性拦下来,并给出“第几行第几列”的精确提示,否则运行时崩溃会极大拖慢迭代效率。国内面试高频追问三点:

  1. Schema 怎么写得既严谨又易扩展;
  2. 验证器如何与 Python 类型系统无缝衔接;
  3. 行列号怎样在报错信息里一次性到位,而不是“JSONDecodeError 只告诉你第几行”。

知识点

  1. JSON Schema 2019-09 核心关键字:type、properties、required、additionalProperties、pattern、minimum、maximum、enum、$ref、definitions。
  2. Python 端校验库:jsonschema(官方参考实现)、fastjsonschema(编译为 Python 字节码,性能高,但行列号需二次定位)。
  3. 行列号定位:标准库 json.loads 只能拿到行号;需用 json.load(fp, object_pairs_hook=OrderedDict) 配合 json.decoder.JSONDecoder 的 pos→lineno/colno 映射,或第三方 python-json-stream 的惰性解析事件。
  4. 自定义错误格式化:继承 jsonschema.exceptions.ValidationError,把 absolute_path 与 instance_pos 映射回行列号。
  5. Pygame 资源热重载:监听文件 mtime,重新校验,行列号报错直接 pygame.event.post 到调试面板,实现“零编译”即时反馈。

答案

  1. 撰写可扩展的 Schema
    把“技能”抽象成三层:根节点 Skill、动画帧数组 Frame、音效节点 Sound。用 $ref 拆分,方便后续技能树、Buff 表复用。
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://example.com/pygame_skill.json",
  "type": "object",
  "definitions": {
    "frame": {
      "type": "object",
      "required": ["duration", "image"],
      "properties": {
        "duration": { "type": "integer", "minimum": 1 },
        "image": { "type": "string", "pattern": "^assets/.+\\.png$" }
      },
      "additionalProperties": false
    },
    "sound": {
      "type": "object",
      "required": ["path", "volume"],
      "properties": {
        "path": { "type": "string", "pattern": "^assets/.+\\.wav$" },
        "volume": { "type": "number", "minimum": 0.0, "maximum": 1.0 }
      }
    }
  },
  "properties": {
    "name": { "type": "string", "minLength": 1 },
    "cooldown": { "type": "number", "minimum": 0 },
    "damage": { "type": "integer", "minimum": 0 },
    "frames": {
      "type": "array",
      "minItems": 1,
      "items": { "$ref": "#/definitions/frame" }
    },
    "sound": { "$ref": "#/definitions/sound" }
  },
  "required": ["name", "cooldown", "damage", "frames"],
  "additionalProperties": false
}
  1. 加载并记录行列号
    使用 json.decoder.JSONDecoder 的底层 scan_once 钩子,在解析的同时把每个 value 的 (lineno, colno, end_lineno, end_colno) 记录到 pos_map[json_path]。
import json
from collections import OrderedDict
from jsonschema import validate, ValidationError, Draft201909Validator

class PositionTrackingDecoder(json.JSONDecoder):
    def __init__(self, *a, **kw):
        super().__init__(*a, **kw)
        self.pos_map = {}
        self.path = []

    def JSONObject(self, s_and_end, strict, scan_once, **kw):
        s, end = s_and_end
        begin_lineno = s.count('\n', 0, end) + 1
        begin_colno = end - s.rfind('\n', 0, end)
        obj, end = super().JSONObject(s_and_end, strict, scan_once, **kw)
        end_lineno = s.count('\n', 0, end) + 1
        end_colno = end - s.rfind('\n', 0, end)
        self.pos_map[tuple(self.path)] = (begin_lineno, begin_colno, end_lineno, end_colno)
        return obj, end

def load_skill(path):
    with open(path, encoding='utf-8') as fp:
        content = fp.read()
    decoder = PositionTrackingDecoder(object_pairs_hook=OrderedDict)
    data = json.loads(content, cls=PositionTrackingDecoder)
    validator = Draft201909Validator(schema)
    errors = sorted(validator.iter_errors(data), key=lambda e: e.path)
    if errors:
        for err in errors:
            path_tuple = tuple(str(p) for p in err.absolute_path)
            ln, cn, *_ = decoder.pos_map.get(path_tuple, (0, 0, 0, 0))
            print(f'{path}:{ln}:{cn}: error: {err.message}')
        raise SystemExit(1)
    return data
  1. 与 Pygame 入口集成
    在 main() 之前统一调用 load_skill,若校验失败直接 pygame.quit() 并弹出 tkinter.messagebox 显示首条错误,保证策划同学一眼看到行列号。

拓展思考

  1. 性能敏感场景(一次性加载数百技能)可把 Schema 预编译为 fastjsonschema.compile,再手写 pos_map 的轻量版本,兼顾毫秒级启动。
  2. 为了支持“技能继承”或“多态”,可在 JSON 里加 "$merge" 与 "$patch" 关键字,自定义 ExtendedValidator 先展开再校验,行列号仍映射回原始文件。
  3. 国内大厂常问“如何防止策划填了 0.999 音量被浮点误差卡阈值”,可在 Schema 用 multipleOf: 0.001 并配合 round(x,3) 的 Python 后处理,验证与运行保持一致。
  4. 若项目转用 YAML(策划更习惯),可用 ruamel.yaml 的 compose() 拿到行号列号,再套同一套 Schema,实现“跨格式统一报错”。