为多个 JSON 模式重用一个对象

reusing an object for multiple JSON schemas

我有两个单独的 JSON 模式(用于验证 REST API 的 HTTP 请求端点),它们都接受完全相同的对象,但具有不同的必填字段(这是一个创建与更新请求)。有没有一种方法可以重用该对象的单个定义并仅更改必填字段?我知道如何使用 $ref 将一个对象重用为另一个对象的 属性,但我不知道如何将整个对象重用为模式中的顶级对象。到目前为止我失败的尝试:

event.json

{
  "id": "event",
  "type": "object",
  "properties": {
    "name": {
      "type": "string"
    },
    "start_date": {
      "type": "integer"
    },
    "end_date": {
      "type": "integer"
    },
    "description": {
      "type": "string"
    }
  },
  "additionalProperties": false
}

事件-create.json

{
  "id": "event-create",
  "type": "object",
  "$ref": "event",
  "additionalProperties": false,
  "required": [ "name", "description" ]
}

显然这是行不通的。它似乎试图将整个 'event' 插入到 'event-create' 的定义中,包括 ID 等。我尝试引用 event#/properties 无济于事。我似乎也无法将 $ref 作为属性 属性 中的唯一值。有什么想法吗?

我发现了一些似乎有效的语法,但我对它不是很满意:

{
  "id": "event-create",
  "allOf": [
    { "$ref": "event" },
    { "required": [ "name", "description" ] }
  ]
}

似乎是对 allOf 运算符的滥用,特别是对于另一种没有必填字段的情况(因此 allof 中只有一个元素)。但它有效,所以除非有人有更好的主意,否则我将继续使用它。

Any members other than "$ref" in a JSON Reference object SHALL be ignored.

- https://datatracker.ietf.org/doc/html/draft-pbryan-zyp-json-ref-03#section-3

这就是您的示例不起作用的原因。 $ref 字段以外的任何内容都应该被忽略。

$ref 的支持仅限于类型为 JSON 架构的字段。这就是为什么尝试将它用于 properties 不起作用的原因。 properties 是一个普通对象,其值为 JSON 模式。

最好的方法是使用 allOf。在这种情况下,allOf 可以被认为是混合模式列表。

{
  "id": "event-create",
  "type": "object",
  "allOf": [{ "$ref": "event" }],
  "required": ["name", "description"]
}