【问题标题】:For json-schema how can I declare a type for the json对于 json-schema,我如何为 json 声明一个类型
【发布时间】:2018-08-04 16:17:28
【问题描述】:

如何声明多个模式并让验证器根据属性选择一个?

例如,我希望根据 type2 的第二个模式验证此 json

{
    "id2": 1,
    "name": "A green door",
    "price": 12.50,
    "tags": ["home", "green"],

    "schemaToValidate" : "type2"
}

类型 1 对象的第一个模式定义:

{
    "$schema": "http://json-schema.org/draft-06/schema#",
    "title": "Product",
    "description": "A product from Acme's catalog",
    "type": "object",
    "required": ["id1"],
    "schemaForType" : "type1"
}

type2 对象的第二个模式定义:

{
    "$schema": "http://json-schema.org/draft-06/schema#",
    "title": "Product",
    "description": "A product from Acme's catalog",
    "type": "object",
    "required": ["id2"],
    "schemaForType" : "type2"
}

我试图在http://json-schema.org/example1.html 找到一个样本,但没有意识到是否可行。

【问题讨论】:

    标签: json jsonschema json-schema-validator


    【解决方案1】:

    根据类型不可能有多个架构,但有一个替代方案:将您的示例更改为使用 oneOf(也简化为在架构上更容易):

    {
        "Type2" : {
          "id2": 1
        }
    }
    

    并且可以添加适用于 Type1 和 Type2 之一的架构:

    {
        "description" : "schema validating Type1 and Type2",
        "type" : "object",
        "oneOf" : [{
            "properties" : {
                "Type1" : {
                    "type": "object",
                    "properties" : {
                        "id1" : {
                            "type" : "integer"
                        }
                    },
                    "additionalProperties": false
                }
            },
            "required" : [ "Type1" ]
        }, {
            "properties" :  {
                "Type2" :  {
                   "type": "object",
                   "properties" :  {
                       "id2" :  {
                          "type" : "integer"
                       }
                  },
                  "additionalProperties" : false
                }
            },
           "required" : ["Type2"]
        }
    ]
    }
    

    Another example of AnyOf

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-09
      • 2020-07-30
      • 2014-07-29
      • 2020-12-26
      • 2023-03-20
      • 2021-09-03
      • 1970-01-01
      • 2021-08-30
      相关资源
      最近更新 更多