重用 JSON 子模式

Reusing JSON subschema

我需要在我的 JSON 文件中多次使用一个子模式,但一直无法找到构建模式文件的正确方法,以便我能够获得该模式验证所有子属性,而不仅仅是我在架构文件中列出的 属性。

这个问题 here 遇到了类似的问题,但答案并不多 sense/I 不确定我是否或如何在这里使用相同的方法。一个 class 的多个实例,我是不是在 OOP 思维模式下想得太多了?

这或多或少是我正在尝试做的事情

{
    "Object1": {
        "Title": "Some Title",
        "Description": "Some Description"
    },
    "Object2": {
        "Title": "Another title",
        "Description": "Another Description"
    }
// unknown number of objects but each object should have the same sub schema
}

这是我目前所拥有的

{
    "$id": "http://example.com/example.json",
    "$schema": "http://json-schema.org/draft-07/schema",
    "required": [
        "Object1"
    ],
    "title": "The root schema",
    "type": "object",
    "properties": {
        "Object1": {
            "required": [
                "Title",
                "Description"
            ],
            "title": "The Reusable Object schema",
            "type": "object",
            "properties": {
                "Title": {
                    "title": "The Title schema",
                    "type": "string"
                },
                "Description": {
                    "title": "The Description schema",
                    "type": "string"
                }
            },
            "additionalProperties": false
        }
    },
    "additionalProperties": true
}

如果对象的所有值都应该遵循架构,解决方案就很简单。

首先,您必须记住 additionalProperties 的工作原理...

The value of "additionalProperties" MUST be a valid JSON Schema.

This keyword determines how child instances validate for objects, and does not directly validate the immediate instance itself.

Validation with "additionalProperties" applies only to the child
values of instance names that do not match any names in "properties", and do not match any regular expression in "patternProperties".

For all such properties, validation succeeds if the child instance validates against the "additionalProperties" schema.

https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-validation-01#section-6.5.6

所以,现在我们知道 additionalProperties 采用 JSON 模式,而不仅仅是布尔值(布尔值是有效的 JSON 模式),解决方案可能有点明显。

去掉最外面的additionalPropertie,重命名propertiesadditionalProperties,去掉键Object1和对象大括号

结果如下...

...
"title": "The root schema",
  "type": "object",
  "additionalProperties": {
    "required": [
      "Title",
      "Description"
    ],
...

现场演示:https://jsonschema.dev/s/pqwCc

虽然我不知道你想用最外面的 required 做什么。我想删除它,因为您事先不知道密钥是什么。

也许您想使用 minProperties 来确保至少有一个?