【问题标题】:how to modify json schema ref to support null type?如何修改 json schema ref 以支持 null 类型?
【发布时间】:2021-06-29 09:28:49
【问题描述】:

现在我有一个像这样的大型 json 架构

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "title": "A example schema",
    "definitions": {
        "stringArray": {
            "type": "array",
            "items": { "type": "string" },
            "uniqueItems": true,
            "default": []
        }
    },
    "properties": {
        "time": {"type": "string", "minLength": 5},
        "id": {"type": "integer"},
        "members": {
             "type": "array",
             "items": {
                 "properties": {
                     "id": {"type": "string"},
                     "email": {"type": "string"}
                 }
             }
        }
    }
}

以及使用它的新架构

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "title": "A example schema",
    "$ref": "example 1"
}

我想修改第二个模式,让一些字段支持空类型。

我正在考虑将第一个模式分成两部分,一个用于不支持 null 的部分,另一个用于需要支持 null 的部分。对于需要支持null的,我需要保留两份,一份支持null类型,一份不支持,因为它们都需要在不同的情况下。

不知道有没有更简单的方法来实现?

【问题讨论】:

    标签: json jsonschema


    【解决方案1】:

    首先,重要的是,草案 7 忽略了任何与 $ref 同级的关键字,因此您需要将 $ref 移动到聚合关键字中(我们在规范中称它们为“应用程序”)。通常使用allOf

    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "title": "A example schema",
      "allOf": [
        { "$ref": "example 1" }
      ]
    }
    

    但对于您的应用程序,您需要使用 oneOf,因为您希望包含另一个允许 null 值的子模式作为选项

    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "title": "A example schema",
      "oneOf": [
        { "$ref": "example 1" },
        { "type": "null" }
      ]
    }
    

    【讨论】:

    • 我不希望这个 ref 支持是 null 类型。我想要的是让那些归档在 ref 支持空类型,例如“时间”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 2013-10-28
    • 2017-02-11
    • 2015-04-15
    相关资源
    最近更新 更多