如何在 jsonschema 中描述这个验证需求?
How to describe this validation requirement in jsonschema?
我想像这样验证我的 API json 回复:
{
"code": 0,
"results": [
{"type":1, "abc": 123},
{"type":2, "def": 456}
]
}
我想验证结果中的对象在类型为 1 时具有 "abc" 字段,在类型为 2 时具有 "def" 字段。结果可能包含任意数量的 type1 和type2 对象。
我可以在 jsonschema 中指定吗?还是我必须对 results
中的元素使用通用验证器并自己进行验证?
您可以使用 anyOf
关键字执行此操作。
An instance validates successfully against this keyword if it validates successfully against at least one schema defined by this keyword's value.
http://json-schema.org/latest/json-schema-validation.html#anchor85
您需要定义这两种类型的项,然后使用 anyOf
来描述 "results" 的数组项。
{
"type": "object",
"properties": {
"code": { "type": "integer" },
"results": {
"type": "array",
"items": { "$ref": "#/definitions/resultItems" }
}
},
"definitions": {
"resultItems": {
"type": "object",
"anyOf": [
{ "$ref": "#/definitions/type1" },
{ "$ref": "#/definitions/type2" }
]
},
"type1": {
"properties": {
"type": { "enum": [1] },
"abc": { "type": "integer" }
},
"required": ["abc"]
},
"type2": {
"properties": {
"type": { "enum": [2] },
"def": { "type": "integer" }
},
"required": ["def"]
}
}
}
我想像这样验证我的 API json 回复:
{
"code": 0,
"results": [
{"type":1, "abc": 123},
{"type":2, "def": 456}
]
}
我想验证结果中的对象在类型为 1 时具有 "abc" 字段,在类型为 2 时具有 "def" 字段。结果可能包含任意数量的 type1 和type2 对象。
我可以在 jsonschema 中指定吗?还是我必须对 results
中的元素使用通用验证器并自己进行验证?
您可以使用 anyOf
关键字执行此操作。
An instance validates successfully against this keyword if it validates successfully against at least one schema defined by this keyword's value.
http://json-schema.org/latest/json-schema-validation.html#anchor85
您需要定义这两种类型的项,然后使用 anyOf
来描述 "results" 的数组项。
{
"type": "object",
"properties": {
"code": { "type": "integer" },
"results": {
"type": "array",
"items": { "$ref": "#/definitions/resultItems" }
}
},
"definitions": {
"resultItems": {
"type": "object",
"anyOf": [
{ "$ref": "#/definitions/type1" },
{ "$ref": "#/definitions/type2" }
]
},
"type1": {
"properties": {
"type": { "enum": [1] },
"abc": { "type": "integer" }
},
"required": ["abc"]
},
"type2": {
"properties": {
"type": { "enum": [2] },
"def": { "type": "integer" }
},
"required": ["def"]
}
}
}