You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否用JSON Schema规范实现业务规则验证?含关联校验需求

问题解答

你的需求可以通过JSON Schema规范实现,不需要完全依赖自定义脚本,但要注意关键字的支持情况:

实现方案(基于Draft-07)

利用JSON Schema的$data关键字(Draft-07引入)结合contains关键字,即可实现跨字段的引用验证。修改后的Schema如下:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
    "books": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "id": { "type": "integer" },
          "title": { "type": "string" },
          "author": {
            "type": "integer",
            "contains": {
              "properties": {
                "id": { "$data": "1/author" }
              },
              "required": ["id"]
            },
            "$data": "/authors"
          }
        },
        "required": ["author"]
      }
    },
    "authors": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "id": { "type": "integer" },
          "name": { "type": "string" }
        },
        "required": ["id"]
      }
    }
  },
  "required": ["books", "authors"]
}

关键逻辑说明

  • $data": "/authors":将当前author字段的验证上下文指向根节点下的authors数组
  • contains关键字:检查authors数组中是否存在至少一个元素满足子Schema规则
  • $data": "1/author":引用当前books项里的author值,要求数组中某个元素的id与该值相等

注意事项

  • 不是所有JSON Schema验证器都默认支持$data关键字,比如Ajv库需要手动启用{ data: true }配置才能生效
  • 如果你的验证环境不支持$data,这种跨字段的引用验证才需要通过自定义脚本实现

内容的提问来源于stack exchange,提问作者sammeh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 19:52:42