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

使用$ref引用的数组元素未被JSON Schema校验,寻求解决方案

问题原因与解决方案

核心问题

根Schema的additionalProperties: false仅对根对象自身生效,不会自动传递给数组中通过$ref引用的子Schema。数组元素的对象校验规则完全由引用的子Schema决定,若子Schema未显式限制额外属性,即使根Schema设置了限制,也无法约束数组内的对象。

解决方案

在被$ref引用的子Schema中,显式添加additionalProperties: false配置,明确限制该对象不允许存在未定义属性。

示例修正

原问题Schema(简化版)

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "additionalProperties": false,
  "properties": {
    "users": {
      "type": "array",
      "items": {
        "$ref": "#/definitions/User"
      }
    }
  },
  "definitions": {
    "User": {
      "type": "object",
      "properties": {
        "name": { "type": "string" },
        "age": { "type": "integer" }
      },
      // 缺失additionalProperties: false
      "required": ["name", "age"]
    }
  }
}

修正后的Schema

在definitions.User中添加additionalProperties: false:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "additionalProperties": false,
  "properties": {
    "users": {
      "type": "array",
      "items": {
        "$ref": "#/definitions/User"
      }
    }
  },
  "definitions": {
    "User": {
      "type": "object",
      "properties": {
        "name": { "type": "string" },
        "age": { "type": "integer" }
      },
      "additionalProperties": false, // 新增此配置
      "required": ["name", "age"]
    }
  }
}

验证效果

测试对象(含未定义的height属性):

{
  "users": [
    { "name": "Alice", "age": 30, "height": 165 }
  ]
}

修正后校验会正常失败,符合预期,因为User子Schema已限制不允许额外属性。

补充说明

如果需要批量给多个子Schema添加额外属性限制,可以使用$defs结合allOf复用规则,避免重复代码:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "additionalProperties": false,
  "properties": {
    "users": { "type": "array", "items": { "$ref": "#/$defs/User" } },
    "products": { "type": "array", "items": { "$ref": "#/$defs/Product" } }
  },
  "$defs": {
    "noExtraProps": { "additionalProperties": false },
    "User": {
      "type": "object",
      "properties": { "name": { "type": "string" }, "age": { "type": "integer" } },
      "required": ["name", "age"],
      "allOf": [{ "$ref": "#/$defs/noExtraProps" }]
    },
    "Product": {
      "type": "object",
      "properties": { "id": { "type": "string" }, "price": { "type": "number" } },
      "required": ["id", "price"],
      "allOf": [{ "$ref": "#/$defs/noExtraProps" }]
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 14:05:10