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

JSON Schema能否指定必填属性存在于顶层对象或数组中任意位置?

可以通过JSON Schema的anyOf组合关键字搭配属性校验规则实现需求,完整可用的Schema如下:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "required": ["name", "records"],
  "properties": {
    "name": {
      "type": "string"
    },
    "swversion": {
      "type": "string"
    },
    "records": {
      "type": "array",
      "items": {
        "type": "object",
        "required": ["time", "temp"],
        "properties": {
          "time": {
            "type": "string"
          },
          "temp": {
            "type": "number"
          },
          "swversion": {
            "type": "string"
          }
        }
      }
    }
  },
  "anyOf": [
    // 分支1:顶层存在swversion
    {
      "required": ["swversion"]
    },
    // 分支2:records数组每一项都存在swversion,匹配示例2场景
    {
      "properties": {
        "records": {
          "items": {
            "required": ["swversion"]
          }
        }
      }
    }
  ]
}

规则说明

  • 基础校验逻辑已经覆盖你已实现的两个要求:顶层必填name和records、records每一项必填time和temp
  • anyOf关键字定义了两个合法的校验分支,只要满足其中任意一个分支就算校验通过:
    • 第一个分支要求顶层对象必须携带swversion属性,不对records内的属性做额外要求,匹配示例1的上报格式
    • 第二个分支要求records数组的每个元素都必须携带swversion属性,不对顶层的swversion做强制要求,匹配示例2的上报格式

如果业务允许records数组只要至少有一条携带swversion就算合法,只需要把第二个分支的items替换为contains关键字即可。如果需要严格禁止swversion同时出现在顶层和records数组内,可以在anyOf的两个分支中分别添加not规则限制另一位置的属性存在。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 22:33:03