如何使 jsonschema 可选?

How can I make jsonschema optional?

{
  "$id": "https://example.com/person.schema.json",
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "Person",
  "type": "object",
  "properties": {
    "firstName": {
      "type": "string",
      "description": "The person's first name."
    },
    "lastName": {
      "type": "string",
      "description": "The person's last name."
    },
    "age": {
      "description": "Age in years which must be equal to or greater than zero.",
      "type": "integer",
      "minimum": 0
    }
  }
  "required": ["firstName", "lastName", "age"]
}

(在@gregdennis 的回答后编辑)

鉴于上述架构,有效数据为

{
  "firstName": "John",
  "lastName": "Doe",
  "age": 21
}

但我想让它成为“可选”,因为我想允许空对象

// should pass
{}

但不是一半模式

// Shouldn't pass
{
    "firstName": "John"
}

你有什么已经是可选的,所以空对象应该通过。为了使这些属性成为必需的,您需要将它们放在 required 关键字中。

"required": [ "first name", "last name", "age" ]

但仅添加此关键字会删除验证空对象的能力。

要解决这个问题,请将其包装在 oneOf 中,询问另一个 接受空对象的模式。

{
  "oneOf": [
    { "const": {} },
    {
      // your schema from above along with required
    }
  ]
}