对于json-schema,我如何为json

时间:2018-02-24 21:12:23

标签: json jsonschema json-schema-validator

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

例如,我希望针对type2

的第二个模式验证此json
{
    "id2": 1,
    "name": "A green door",
    "price": 12.50,
    "tags": ["home", "green"],

    "schemaToValidate" : "type2"
}

type1对象的第一个模式定义:

{
    "$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找到一个样本但是没有意识到是否可能。

1 个答案:

答案 0 :(得分:2)

根据类型不可能有多个架构,但有另一种选择:更改您的示例以使用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